我必须在表单中获取一些元素才能更改onchange
的的样式。我添加了类new_cat_inputs
的元素,我想我会得到他们document.querySelectorAll()
。
我试过很多东西,但它从来没有工作过,我终于用:JS - 理解具有类名称的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,你尝试把你的代码,这个事件监听器里:'窗口.addEventListener('DOMContentLoaded',function(){ //您的代码 })' ? –
@boehm_s你是对的,'window.onload'不够用 – AymDev
但仍然...为什么'document.getElementsByClassName()'工作,而不是'document.querySelectorAll()'? @boehm_s – AymDev