Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get all direct children

I need to get all the direct children of an element. As it is here:

<div class='1'>
    <div class='2'>
        <div class='3'></div>
    </div>
    <div class='2'></div>
</div>

I need the two DIVs with class "2" using the one with class "1". Plain JavaScript - no libraries.

(They are the same class in this example just to be more clear. In my need they are with different, unknown classes.)

like image 589
Krupp Avatar asked Jan 24 '16 02:01

Krupp


1 Answers

One option is to use the direct child combinator, >, and the universal selector, *, in order to select direct children elements of any type:

document.querySelectorAll('.element > *');

Alternatively, there is also a .children property that will return all the direct children elements:

document.querySelector('.element').children;
like image 95
Josh Crozier Avatar answered Nov 02 '22 21:11

Josh Crozier