0

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.

2 Answers 2

2

Probably you're pushing the result of Array.from, which is an array.

To get all of them into a single Array, you need to concatenate the result (Array.from) for each iteration.

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.