Javascript document.querySelector返回null,但元素存在
目前,我正在尝试使用javascript根据页眉和页脚的高度设置中心元素(class='main')高度的自动更改。脚本如下所示:Javascript document.querySelector返回null,但元素存在,javascript,error-handling,Javascript,Error Handling,目前,我正在尝试使用javascript根据页眉和页脚的高度设置中心元素(class='main')高度的自动更改。脚本如下所示: const headerHeight = document.querySelector('header').clientHeight; const footerHeight = document.querySelector('footer').clientHeight; const mainElement = document.querySelector('main
const headerHeight = document.querySelector('header').clientHeight;
const footerHeight = document.querySelector('footer').clientHeight;
const mainElement = document.querySelector('main');
changeMainBlockHeight();
function changeMainBlockHeight() {
const resultMainHeight = pageHeight - headerHeight - footerHeight;
mainElement.setAttribute('style', `height: ${resultMainHeight}px`);
}
如果我在querySelector主元素中选择,您可以看到一切正常,没有错误,元素的总和高度实际上是100vh:。
但如果我在第三个代码行const main element=document.querySelector('main')
中选择container而不是main元素(这是main元素的第一个子元素),并且该行变为const main element=document.querySelector('container')
,则会出现以下错误:
除容器外,其他一些元素也会出现这种情况,但我认为这就足以作为一个示例。
此外,此警告经常出现:“版面在页面完全加载之前已被强制。如果尚未加载样式表,则可能会导致未设置样式的内容闪烁。”。这可能与发生的错误有关,但我无法找到原因和解决方案。
如果有任何帮助,我将不胜感激!:)
列表项您的容器是一个带类容器的div,因此您应该查询“.container”(带点)而不仅仅是“container”当您使用查询选择器时,您必须精确到让它能够理解 如果要调用HTML标记,如
body
、div
或p
,则无需在queryselector的字符串中添加任何其他内容
但是在这里,由于您想要调用一个类,因此必须在类名之前使用符号“.”来向查询选择器指定您正在查找的类
const mainElement = document.querySelector('.main');
这同样适用于ID和#。请共享您试图查询的相应HTML。最有可能的情况是,您使用的是带有类容器的div,必须使用
document.querySelector('.container')
查询该类容器。它只能从您的HTML中确认。谢谢您的回答!我以为我正在使用我命名的类访问main、footer和header元素,但我不明白为什么querySelector没有看到其他元素。谢谢你的回答!我以为我正在使用我命名的类访问main、footer和header元素,但我不明白为什么querySelector看不到其他元素。