找到父纯纯JavaScript的子元素 [英] Finding child element of parent pure javascript
问题描述
最有效的方法是使用纯JavaScript查找特定父元素的(含有类或ID)的子元素。没有jQuery或其他框架。
What would the most efficient method be to find a child element of (with class or ID) of a particular parent element using pure javascript only. No jQuery or other frameworks.
在这种情况下,我需要找到 child1 或 child2 > parent ,假设DOM树可以在树中具有多个 child1 或 child2 类元素。我只想要父元素
In this case, I would need to find child1 or child2 of parent, assuming that the DOM tree could have multiple child1 or child2 class elements in the tree. I only want the elements of parent
<div class="parent">
<div class="child1">
<div class="child2">
</div>
</div>
</div>
推荐答案
children
property返回一个元素数组,如下所示:
The children
property returns an array of elements, like so:
parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]
querySelector旧版浏览器不支持
。有一些选择,如 document.getElementsByClassName('parent')[0]
如果你愿意的话。
querySelector
is relatively new and not supported in older browsers. There are alternatives, like document.getElementsByClassName('parent')[0]
if you so desire.
编辑:现在我想到了,你可以使用 querySelectorAll
获得 parent
有一个类名为 child1
:
Now that I think about it, you could just use querySelectorAll
to get decendents of parent
having a class name of child1
:
children = document.querySelectorAll('.parent .child1');
qS和qSA之间的区别是后者返回匹配的所有元素选择器,而前者只返回第一个这样的元素。
The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.
这篇关于找到父纯纯JavaScript的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!