简体   繁体   English

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>

I need the two DIVs with class "2" using the one with class "1". 我需要使用类“1”的两个DIV和类“1”。 Plain JavaScript - no libraries. 普通的JavaScript - 没有库。

(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 > *');

Alternatively, there is also a .children property that will return all the direct children elements: 或者,还有一个.children属性将返回所有直接子元素:

document.querySelector('.element').children;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM