2011-06-10 85 views
8

至於我也明白了,querySelector返回一個真正的可變因素,而querySelectorAll返回非現場靜態節點集。querySelectorAll:操作節點

我想調整安裝到特定選擇的所有元素的風格。它工作正常的第一要素與querySelector,但不是與querySelectorAll所有匹配的元素。我想這是因爲節點集是非活的。

是否有解決方法?或者我錯過了什麼?

回答

9

的問題是,querySelector返回單個節點。 querySelectorAll返回一組節點(活躍性意味着如果更新它們,組合中的元素將不會被刪除)。你需要在每個匹配的元素上設置一個樣式,可能會有一個循環 - 你不能只爲它們設置一個屬性。

所以,你可能需要做這樣的事情:

var nodes = document.querySelectorAll('div.foo'); 
for (var i = 0; i < nodes.length; i++) { 
    nodes[i].style.color = 'blue'; 
} 
+0

非常感謝!我嘗試過,但它不起作用,所以我認爲這是由於nodeset沒有生效。但實際上我剛纔忘了初始化迭代器(= 0)... – fabb 2011-06-11 09:28:48

5

這也將工作..

[].forEach.call(document.querySelectorAll('div.foo'), function (el) { 
    el.style.color = 'blue'; 
}); 
+0

它讓我感興趣的是,以上的作品,但'document.querySelectorAll(「div.foo」)的forEach(函數(E1)...'沒有按「T工作的任何想法,爲什麼 – 2015-01-29 03:51:38

+1

querySelectorAll返回一個節點列表,它不具有的forEach參見:?https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F – seans 2015-02-24 15:44:01

1

querySelectorAll: manipulating nodes但有辦法描述,使其工作,因爲forEach只適用於陣列,不適用於NodeLists:

Array.prototype.slice.call(document.querySelectorAll('div.foo')).forEach(function(el) { 
    el.style.color = 'blue'; 
});