Javascript get all direct children

删除回忆录丶 提交于 2019-12-01 15:08:32

问题


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.)


回答1:


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;


来源:https://stackoverflow.com/questions/34971668/javascript-get-all-direct-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!