我必须在表单中获取一些元素来更改其样式 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 时更新。
干杯,
关于javascript - document.body.querySelectorAll() 失败,但 document.getElementsByClassName() 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065115/