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

document.body.querySelectorAll() fails but document.getElementsByClassName() works

我必须在表单中获取一些元素来更改 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 经常有帮助但这次没有。

select 多个 DOM 元素 在 [=26] 中的 class 的正确方法是什么=]整个文档 由函数 document.querySelectorAll() ?

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

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

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

the following link

干杯,