Javascript get all straight kids

I need to get all direct children. How is he here:

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

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

(This is the same class in this example, to be more clear. In my need, they have different unknown classes.)

+5
source share
1 answer

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

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

As an alternative, there is also a .children property that returns all direct children:

 document.querySelector('.element').children; 
+4
source

Source: https://habr.com/ru/post/1241341/


All Articles