DOMメソッドdocument.querySelectorAll()
(および他のいくつかのメソッド)はを返しますNodeList
。
リストを操作するには、たとえばを使用してforEach()
、NodeList
最初にに変換する必要がありArray
ます。
変換するための最良の方法何NodeList
にはArray
?
DOMメソッドdocument.querySelectorAll()
(および他のいくつかのメソッド)はを返しますNodeList
。
リストを操作するには、たとえばを使用してforEach()
、NodeList
最初にに変換する必要がありArray
ます。
変換するための最良の方法何NodeList
にはArray
?
回答:
ES6を使用すると、次のことが簡単にできます。
const spanList = [...document.querySelectorAll("span")];
Type 'NodeListOf<Element>' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)
ES6ではを使用できますArray.from(myNodeList)
。次に、お気に入りの配列メソッドを使用します。
var myNodeList = document.querySelectorAll('.my-selector');
// ALT 1
Array.from(myNodeList).forEach(function(el) {
console.log(el);
});
ES6シムを使用して、古いブラウザーでもこれを機能させます。
トランスパイラー(Babelなど)を使用している場合は、さらに2つの選択肢があります。
var myNodeList = document.querySelectorAll('.my-selector');
// ALT 2
for (var el of myNodeList) {
el.classList.add('active'); // or some other action
}
// ALT 3
[...myNodeList].forEach((el) => {
console.log(el);
});
Array.from(myNodeList)
。
プロトタイプのslice
メソッドを使用して、配列に変換できますArray
。
var elList = document.querySelectorAll('.viewcount');
elList = Array.prototype.slice.call(elList, 0);
Furthermore, if all you need is forEach
, you can invoke that from the Array
prototype, without coercing it to an array first:
var elList = document.querySelectorAll('.viewcount');
Array.prototype.forEach.call(elList, function(el) {
console.log(el);
});
In ES6, you can use the new Array.from
function to convert it to an array:
Array.from(elList).forEach(function(el) {
console.log(el);
});
This is currently only in bleeding edge browsers, but if you're using a polyfill service you will have access to this function across the board.
If you're using an ES6 transpiler, you can even use a for..of
loop instead:
for (var element of document.querySelectorAll('.some .elements')) {
// use element here
}
Array.prototype.forEach
instead of [].forEach
, is because the latter creates a new Array object, which is totally unnecessary.
[]
? My thinking is that it would get garbage collected and the memory impact is negligible, can anyone comment on this?
Why convert? - just call
function of Array directly on element collection ;)
[].forEach.call( $('a'), function( v, i) {
// do something
});
assuming $ is your alias for querySelectorAll, of course
edit: ES6 allows for even shorter syntax [...$('a')]
(works in Firefox only, as of May 2014)
$
is querySelectorAll
.
function $ ( s ) { return document.querySelectorAll(s); }
.
$('a').each(function(i, v) {...});
Older browsers can use the polyfill below.
To operate on the list in javascript, e.g. using forEach(), the NodeList must be converted to an Array.
That's not true. .forEach()
works in current browsers. If it's missing, you can use a polyfill to add .forEach() from Array to NodeList and it works fine:
if ( ! NodeList.prototype.forEach ) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
You can now run:
myNodeList.forEach(function(node){...})
To iterate over NodeLists just like Arrays.
This produces much shorter and cleaner code than .call() everywhere.
forEach
specifically, I came here looking for filter
filter
, but you may wish to give it an unofficial name NodeList.prototype.dbkFilter
or similar if you're worried about a future standard using a different implementation .
Does it have to be forEach
? You could simply use a for
loop to iterate over the list:
for (var i = 0; i < elementList.length; i++) {
doSomethingWith(elementlist.item(i));
}
elementList.item(i)
, you could just use elementList[i]
.
forEach()
a better programming style and less verbose - ymmv
for (var oElement, i = 0; oElement = aMenuItemsElements; i++ { console.log(oElement); }
for (var i…)
loop because the for loop doesn’t create its own scope (like it does in C/C++ now). And then the i
get mixed up.
ES6 allows cool ways like var nodeArray = Array.from(nodeList)
but my favorite one is the new spread operator.
var nodeArray = Array(...nodeList);
That worked with me in ES6
lets assume you have nodelist like that
<ul>
<li data-time="5:17">Flexbox video</li>
<li data-time="8:22">Flexbox video</li>
<li data-time="3:24">Redux video</li>
<li data-time="5:17">Flexbox video</li>
<li data-time="7:17">Flexbox video</li>
<li data-time="4:17">Flexbox video</li>
<li data-time="2:17">Redux video</li>
<li data-time="7:17">Flexbox video</li>
<li data-time="9:54">Flexbox video</li>
<li data-time="5:53">Flexbox video</li>
<li data-time="7:32">Flexbox video</li>
<li data-time="2:47">Redux video</li>
<li data-time="9:17">Flexbox video</li>
</ul>
const items = Array.from(document.querySelectorAll('[data-time]'));
console.log(items);
Well, this works for me too:
const elements = Object.values( document.querySelector(your selector here) )
Object.values()
returns Array
of values of given object. NodeList
is object, as is everything in JS.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
But it's not compatible with IE, so i guess Array.prototype.*array_method*.call(yourNodeList)
is the best option. With this you can invoke any array method on your NodeList
Assuming elems is a nodeList:
var elems = document.querySelectorAll('select option:checked');
then it can be turned into an array as follows:
var values = [].map.call(elems, function(obj) {
return obj.value;
});