[英]Selecting elements based on name attribute
I have an array of each element's attribute. 我有每个元素的属性的数组。 I want to get all elements from that array by looping through the array.
我想通过遍历数组从数组中获取所有元素。 This is what I tried:
这是我尝试的:
var array = ["blue", "yellow", "red"]; // these are name attributes of elements
for(var i=0; i<array.length; i++) {
var elements = Array.from(document.querySelectorAll("div[name="+array[i]+"]"));
}
Problem is that I get three separated arrays, I want one with all elements in it. 问题是我得到了三个分离的数组,我想要一个包含所有元素的数组。
Probably you're pushing the result of Array.from
, which is an array. 可能您要推送
Array.from
的结果,它是一个数组。
To get all of them into a single Array, you need to concatenate the result ( Array.from
) for each iteration. 为了将所有这些都放入单个Array中,您需要为每次迭代连接结果(
Array.from
)。
var array = ["blue", "yellow", "red"]; // these are name attributes of elements var elements = []; for (var i = 0; i < array.length; i++) { elements = elements.concat(Array.from(document.querySelectorAll("div[name=" + array[i] + "]"))); } console.log(elements)
<div name='blue'></div> <div name='red'></div> <div name='yellow'></div>
have you tried: 你有没有尝试过:
var array = ["blue", "yellow", "red"]; // these are name attributes of elements var query = array.map(name => "div[name="+name+"]").join(', '); var elements = Array.from(document.querySelectorAll(query)); console.log(elements)
<div name="blue"></div> <div name="yellow"></div> <div name="red"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.