Javascript得到所有直接的孩子 [英] 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>
我需要使用类1的两个DIV和类2。简单的JavaScript - 没有库。
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.)
推荐答案
一种选择是使用直接子组合子,>
,以及通用选择器 *
,为了选择任何类型的直接子元素:
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 > *');
另外,还有 .children
property 将返回所有直接子元素:
Alternatively, there is also a .children
property that will return all the direct children elements:
document.querySelector('.element').children;
这篇关于Javascript得到所有直接的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!