Reputation: 4938
I am trying to concat two nodelists using
var ul = document.querySelector("ul");
var down = document.getElementsByClassName("mobile")[0];
var ul_child = Array.prototype.concat.call(ul.children,down.children);
But this returns only two nodes from ul nodelist and ignore others. What is the most valid to concat two nodelsits? I would like to avoid brute looping them
Upvotes: 34
Views: 25926
Reputation: 945
And yet another approach:
document.querySelectorAll([".foo", ".bar"])
Will return a normal NodeList with all of the above matching, in the order in which they are found in the DOM.
Upvotes: 1
Reputation: 1
Ok, I guess that the spread operator was pretty new, when this question was posted. But it is possible to do it this way also
const list1 = document.querySelectorAll(".some-selector")
const list2 = document.querySelectorAll(".some-other-selector")
const filters = Array.prototype.concat.call(...list1 , ...list2 )
Upvotes: 0
Reputation: 2049
Set() ensures items are unique and the ES6 Spread operator makes it neat & tidy:
var elems = new Set([
...document.querySelectorAll(query1),
...document.querySelectorAll(query2)
]);
Upvotes: 28
Reputation: 591
This is a bit of a different approach, but perhaps you could try combining them in your query selector:
var ul_down = document.querySelectorAll("ul,.mobile:first-child");
Upvotes: 11
Reputation: 12508
You can try converting the two NodeList
objects to arrays first. Then calling concat
on the results:
// Convert the first list to an array
var ul_list = document.querySelector("ul"),
ul_children_array = Array.prototype.slice.call(ul_list.children);
// Convert the second list to an array
var down_list = document.getElementsByClassName("mobile")[0],
down_children_array = Array.prototype.slice.call(down_list.children);
var ul_child_array = Array.prototype.concat.call(ul_children_array, down_children_array);
Upvotes: 8
Reputation: 207557
Why don't you use one selector to select them at the same time than you do not need to concat them and you end up with an HTML Collection instead of an Array.
var elems = document.querySelectorAll("ul > li, .mobile > *");
console.log(elems);
<ul><li>x</li></ul>
<div class="mobile">y</div>
Upvotes: 60