简体   繁体   English

document.querySelector 返回 null,但元素存在

[英]document.querySelector returns null, but element exists

At the moment, I'm trying to set up an automatic change in the height of the center element (class='main') depending on the height of the header and footer using javascript.目前,我正在尝试使用 javascript 根据页眉和页脚的高度设置中心元素 (class='main') 高度的自动更改。 The script is like this:脚本是这样的:

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`);
}

If i choose in querySelector main element, you can see that everything is normal, no errors, and the summ height of the elements is really 100vh: no error .如果我在 querySelector 主元素中选择,可以看到一切正常,没有错误,元素的总和高度真的是 100vh: no error But if I choose container instead of the main element (this is the first child element of the main element) in the 3rd code line const mainElement = document.querySelector('main') , and line becomes const mainElement = document.querySelector('container') i get this error: error但是,如果我在第 3 行代码const mainElement = document.querySelector('main')选择容器而不是主元素(这是主元素的第一个子元素const mainElement = document.querySelector('main') ,则行变为const mainElement = document.querySelector('container')我收到此错误:错误
This also happens with some other elements other than the container, but I think this is enough for an example.这也发生在容器以外的其他一些元素上,但我认为这足以作为一个例子。
Also, this warning often appears :"Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content.".此外,这个警告经常出现:“在页面完全加载之前强制布局。如果尚未加载样式表,这可能会导致无样式内容的闪烁。”。 This may have something to do with the error that occurs, but I couldn't find a cause and solution.这可能与发生的错误有关,但我找不到原因和解决方案。
I will be grateful for any help!我将不胜感激任何帮助! :) :)

List item项目清单

你的容器是一个带有类容器的 div,所以你应该查询“.container”(带点)而不仅仅是“container”

When you use the query selector, you have to be precise for it to understand.当您使用查询选择器时,您必须准确理解它。

If you want to call an HTML tag like body , div or p you don't need to put anything else in your string for queryselector.如果你想调用像bodydivp这样的 HTML 标签,你不需要在查询选择器的字符串中添加任何其他内容。

But here, since you want to call a class, you have to use the notation "."但是在这里,由于要调用类,必须使用符号“.”。 before your class name to specify to the query selector that you are looking for a class.在您的类名之前指定您正在查找的类的查询选择器。

const mainElement = document.querySelector('.main');

The same applies for ids and the #.这同样适用于 id 和 #。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM