[英]How to loop through selected elements with document.querySelectorAll
I am trying loop on selected elements that queried with document.querySelectorAll, but how?我正在尝试循环使用 document.querySelectorAll 查询的选定元素,但是如何?
For example I use:例如我使用:
var checkboxes = document.querySelectorAll('.check');
for( i in checkboxes) {
console.log(checkboxes[i]);
}
Output: Output:
<input id="check-1" class="check" type="checkbox" name="check">
<input id="check-2" class="check" type="checkbox" name="check">
<input id="check-3" class="check" type="checkbox" name="check">
<input id="check-4" class="check" type="checkbox" name="check">
<input id="check-5" class="check" type="checkbox" name="check">
<input id="check-6" class="check" type="checkbox" name="check">
<input id="check-7" class="check" type="checkbox" name="check">
<input id="check-8" class="check" type="checkbox" name="check">
<input id="check-9" class="check" type="checkbox" name="check">
<input id="check-10" class="check" type="checkbox" name="check" checked="">
10
item()
namedItem()
My problem is that at the end this method returns 3 extra items.我的问题是最后这个方法返回 3 个额外的项目。 How can I properly do it?
我怎样才能正确地做到这一点?
My favorite is using spread syntax to convert the NodeList to an array and then use forEach
for looping.我最喜欢的是使用扩展语法将 NodeList 转换为数组,然后使用
forEach
进行循环。
var div_list = document.querySelectorAll('div'); // returns NodeList
var div_array = [...div_list]; // converts NodeList to Array
div_array.forEach(div => {
// do something awesome with each div
});
I code in ES2015 and use Babel.js, so there shouldn't be a browser support issue.我在 ES2015 中编码并使用 Babel.js,所以不应该存在浏览器支持问题。
for in
loop is not recommended for arrays and array-like objects - you see why.不建议将
for in
循环用于数组和类似数组的对象 - 你明白为什么。 There can be more than just number-indexed items, for example the length
property or some methods, but for in
will loop through all of them.不仅可以有数字索引项,例如
length
属性或某些方法,而且for in
将遍历所有这些项。 Use either使用任一
for (var i = 0, len = checkboxes.length; i < len; i++) {
//work with checkboxes[i]
}
or或者
for (var i = 0, element; element = checkboxes[i]; i++) {
//work with element
}
The second way can't be used if some elements in array can be falsy (not your case), but can be more readable because you don't need to use []
notation everywhere.如果数组中的某些元素可能是虚假的(不是您的情况),则不能使用第二种方法,但可以更具可读性,因为您不需要在任何地方使用
[]
表示法。
It looks like Firefox 50+, Chrome 51+ and Safari 10+ now all support the .forEach
function for NodeList
objects.看起来 Firefox 50+、Chrome 51+ 和 Safari 10+ 现在都支持
NodeList
对象的.forEach
函数。 Note— .forEach
is not supported in Internet Explorer , so consider one of the approaches above or use a polyfill if IE support is required.注意 -
.forEach
在 Internet Explorer 中不受支持,因此请考虑上述方法之一,或者如果需要 IE 支持,请使用 polyfill。
https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
const paragraphs = document.querySelectorAll('p'); paragraphs.forEach(p => console.log(p));
<p>paragraph 1</p> <p>paragraph 2</p> <p>paragraph 3</p> <p>paragraph 4</p> <p>paragraph 5</p>
With ES6 , there is a static method Array.from
to take advantages of Array
non-static methods (map, filter, ...) :在ES6中,有一个静态方法
Array.from
可以利用Array
非静态方法(map、filter、...):
Array.from(document.querySelectorAll('div')).forEach((element,index) =>
{
// handle "element"
});
Another use of Array.from
since querySelector
provides item
method: Array.from
的另一个用途,因为querySelector
提供了item
方法:
var all = document.querySelectorAll('div');
// create range [0,1,2,....,all.length-1]
Array.from({length: all.length}, (v, k) => k).forEach((index) => {
let element = all.item(index);
});
A nice alternative is:一个不错的选择是:
[].forEach.call(
document.querySelectorAll('.check'),
function (el) {
console.log(el);
}
);
but as pointed out, you should use a for loop.但正如所指出的,您应该使用 for 循环。
.map
will not work directly on a NodeList
but will on an Array
. .map
不能直接在NodeList
上工作,但可以在Array
上工作。
Compare these: Array.prototype.map()
NodeList.forEach()
比较这些:
Array.prototype.map()
NodeList.forEach()
[...element_list]
then Array.map()
[...element_list]
然后Array.map()
Array.from()
on a NodeList.forEach()
Array.from()
NodeList.forEach()
NodeList.forEach()
for
loop"for
循环”The shortest and cleanest way to be able to use any regular Array methods, or in your case a for in
loop on a NodeList
, is to spread it into an array as you fetch it:能够使用任何常规 Array 方法的最短和最简洁的方法,或者在您的情况下是
NodeList
上的for in
循环,是在您获取它时将其传播到一个数组中:
const checkboxes = [...document.querySelectorAll('.check')];
for (i in checkboxes) {
console.log(checkboxes[i]);
}
For me the most clean and accessible is for of
syntax.对我来说,最干净、最容易理解的是
for of
语法。 The second options for me is the spread operator ( ...
) if ES6 is available.如果 ES6 可用,我的第二个选项是扩展运算符 (
...
)。 Finally, forEach
if you are building big app and you want to provide support for most of the browsers out there.最后,如果您正在构建大型应用程序并且想要为大多数浏览器提供支持,请
forEach
。
const lis = document.querySelectorAll('li') let results = { 'for': [], 'forEach': [], 'three-dots': [], } // ES6 bellow for (const li of lis) { results['for'].push(li) } // ES6 above [...lis].forEach((li) => results['three-dots'].push(li)) // Most browsers support it lis.forEach(li => results['forEach'].push(li)) console.log({results})
<u> <li>Item 01</li> <li>Item 02</li> <li>Item 03</li> <li>Item 04</li> <li>Item 05</li> <li>Item 06</li> <li>Item 07</li> <li>Item 08</li> </u>
// for class
for (const elem of document.querySelectorAll('[class=".check"]'){
//work as per usual
});
// for name
for (const elem of document.querySelectorAll('[name="check"]'){
//work as per usual
});
// for id
for (const elem of document.querySelectorAll('[id="check-1"]'){
//work as per usual
});
This provides me with flexibility on what element I would like to work with.这为我提供了我想要使用的元素的灵活性。
U can select all elements using querySelectorAll
method.您可以使用
querySelectorAll
方法选择所有元素。 It will return an array of nodeList.它将返回一个 nodeList 数组。
Lets say u want to select all p tags假设你想选择所有 p 标签
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
<p>paragraph 4</p>
<p>paragraph 5</p>
const paragraphs = document.querySelectorAll('p');
Now the paragraphs has a forEach method which can be used to loop through the nodelist现在段落有一个 forEach 方法,可用于循环遍历节点列表
paragraphs.forEach(console.log); (logs node)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.