2017-02-06 29 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

相關問題