查找父纯javascript的子元素 [英] Finding child element of parent pure javascript
问题描述
最有效的方法是仅使用纯 javascript 查找特定父元素的(带有类或 ID)的子元素.没有 jQuery 或其他框架.
在这种情况下,我需要找到 parent 的 child1 或 child2,假设 DOM 树可以有多个 树中的 child1 或 child2 类元素.我只想要 parent
的元素 <div class="child1"><div class="child2">
children
属性返回一个元素数组,如下所示:
parent = document.querySelector('.parent');孩子 = parent.children;//[<div class="child1">]
querySelector
有其他选择,例如 document.getElementsByClassName('parent')[0]
如果你愿意的话.
现在我考虑了一下,您可以使用 querySelectorAll
来获取具有 child1
类名称的 parent
的后代:
children = document.querySelectorAll('.parent .child1');
qS 和 qSA 的区别在于后者返回所有与选择器匹配的元素,而前者只返回第一个这样的元素.
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.
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>
The children
property returns an array of elements, like so:
parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]
There are alternatives to querySelector
, like document.getElementsByClassName('parent')[0]
if you so desire.
Edit: 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');
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屋!