Reputation: 1781
I searched a lot for an answer, but I didn't find any proper solution.
I'd like to get all HTML elements that are inside of all divs with the same className, but it is important all of them be part of the same collection, or array or anything that allow me to loop through it.
Let's say that I have two divs
with a class called 'divTest', if I use querySelectorAll
to reach it I will get a childList with two indexes, 0 for the first div
and 1 for the second. It would give me all elements inside these divs
, but they wouldn't be together. I'd like to access both indexes at once.
I am accessing each element by its index and putting it inside an array, where I spread both:
submits = document.querySelectorAll(".divTest")[0].children;
submits1 = document.querySelectorAll(".divTest")[1].children;
arrayTeste = [...submits, ...submits1]
It works, but I'd like to know if there is a direct way to do this, like accessing both indexes on the same code line?
Upvotes: 4
Views: 3794
Reputation: 370659
Use .divTest > *
to select all elements which are immediate children of an element with a divTest
class:
console.log(
document.querySelectorAll('.foo > *').length
);
<div class="foo">
<div></div>
<div></div>
</div>
<div class="foo">
<div></div>
<div></div>
</div>
Upvotes: 6