2017-02-06 21 views
0

我必须在表单中获取一些元素才能更改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元素通过类的正确方法是什么?

+1

在你的榜样,document.body的是'null',所以也许没有加载你的DOM,你尝试把你的代码,这个事件监听器里:'窗口.addEventListener('DOMContentLoaded',function(){ //您的代码 })' ? –

+0

@boehm_s你是对的,'window.onload'不够用 – AymDev

+0

但仍然...为什么'document.getElementsByClassName()'工作,而不是'document.querySelectorAll()'? @boehm_s – AymDev

回答

1

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

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

我认为(我不知道),其YOUT getElementsByClassName工作,因为你在另一个地方,或当用它DOM已加载。并且由于此方法返回直播HTMLCollection,它在DOM已加载时更新。

the following link

干杯,

+0

我在同一个地方使用了这两个函数,但是你关于实时'HTMLCollection'的解释更有意义。非常感谢,我今天学到了! – AymDev

相关问题