【问题标题】:document.body.querySelectorAll() fails but document.getElementsByClassName() worksdocument.body.querySelectorAll() 失败,但 document.getElementsByClassName() 有效
【发布时间】: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


【解决方案1】:

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

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

我认为(我不确定)你 getElementsByClassName 工作是因为你在另一个地方使用它或在加载 DOM 时使用它。由于此方法返回 live HTMLCollection,因此在加载 DOM 时会更新它。

the following link

干杯,

【讨论】:

  • 我在同一个地方使用了这两个函数,但你对直播HTMLCollection 的解释更有意义。非常感谢,今天学到了!
猜你喜欢
  • 2014-06-07
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2017-08-18
  • 1970-01-01
  • 2020-10-06
相关资源
最近更新 更多