【发布时间】:2017-06-23 05:41:34
【问题描述】:
我必须在表单中获取一些元素来改变它们的样式 onchange 或 <select>。我将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 没有加载,你有没有尝试把你的代码放在这个事件监听器中:window.addEventListener('DOMContentLoaded', function() { // your code })? -
@boehm_s 你是对的,
window.onload还不够 -
但仍然......为什么
document.getElementsByClassName()有效,而不是document.querySelectorAll()? @boehm_s
标签: javascript html dom css-selectors selectors-api