javascript - document.body.querySelectorAll() 失败,但 document.getElementsByClassName() 有效

标签 javascript html dom css-selectors selectors-api

我必须在表单中获取一些元素来更改其样式 onchange<select> 。我添加了类(class)new_cat_inputs到元素,我想我可以通过 document.querySelectorAll() 得到它们.
我尝试了很多东西,但从来没有成功,我终于使用了:

document.getElementsByClassName("new_cat_inputs")

这意味着我的问题已经解决了,但我想了解一下。
这是我之前尝试过的:

// first attempt, as I'd have used document.querySelector() which works this way
document.querySelectorAll(".new_cat_inputs");

// Logs an error which says it can't read the property "querySelectorAll" of null (body)
document.body.querySelectorAll(".new_cat_inputs");

// doesn't get the elements neither as the 1st attempt. Neither with document.body
document.querySelectorAll("label.new_cat_inputs, input.new_cat_inputs, select.new_cat_inputs");

我读了MDN documentation这通常会有所帮助,但这次没有。

通过函数 document.querySelectorAll()整个文档中按选择多个 DOM 元素的正确方法是什么? ?

最佳答案

由于 document.body 在您的示例中似乎为 null,这意味着 DOM 未加载。 以下事件监听器允许您等待 DOM 加载,然后执行代码:

window.addEventListener('DOMContentLoaded', function() {
  // your code
})

我认为(我不确定)您 getElementsByClassName 有效是因为您在其他地方或加载 DOM 时使用了它。由于此方法返回一个 live HTMLCollection,因此它会在加载 DOM 时更新。

参见the following link

干杯,

关于javascript - document.body.querySelectorAll() 失败,但 document.getElementsByClassName() 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065115/

相关文章:

javascript - 仅使用 Javascript 设置 HR 标签的宽度

javascript - 页面重新加载后在url中添加 anchor 并在JS中显示隐藏部分

javascript - 当用户单击链接时执行功能的最佳方式是什么?

html, css - 如何使用显示 : inline-block

javascript - 如何获取没有页面的url

html - 悬停和下拉子菜单

javascript - Chrome : Disable same origin policy for localhost

javascript - jQuery点击后如何保持当前宽度/高度?

javascript - 在输入文本框中输入时显示图标

html - HTML 表单元素和 POSTed 数据中的层次结构