如何仅对元素的子元素运行getElementsByTagName? [英] How to run getElementsByTagName on children of an element only?
问题描述
我无法让选择器正常工作。
I'm having trouble getting a selector to work properly.
我有这个HTML:
<div.wrapper>
<div.ui-controlgroup-controls>
<form>
<div.ui-btn></div>
</form>
<div.ui-btn></div>
<div.ui-btn></div>
<div.ui-btn></div>
<div.ui-btn></div>
</div>
</div>
我正在尝试选择 div
标签,是 ui-controlgroup-controls
的子项 - 这意味着排除表单中的内容。
and I'm trying to select the div
tags, which are children of ui-controlgroup-controls
- which means excluding whats inside the form.
这我正在尝试:
// el is my div.wrapper element
el.children[0].getElementsByTagName("div");
但是这不起作用,因为表单中的div最终会出现在选择中。
However this does not work, because the div inside the form ends up in the selection.
问题:
如果我不想使用jQuery,如何正确选择元素?
Question:
How can I select the elements correctly when I don't want to use jQuery?
推荐答案
执行此操作的一种方法是迭代结果节点列表并检查父节点:
One way to do this is to iterate over your resulting node list and check the parent:
var nodes = el.children[0].getElementsByTagName("div");
nodes = Array.prototype.slice.call(nodes);
nodes = nodes.filter(function(v, i){
return v.parentElement === el.children[0];
});
以下是这种方法的演示: http://jsfiddle.net/WLhY2/
Here is a demonstration of this approach: http://jsfiddle.net/WLhY2/
更简单(尽管效率更低)的方法是使用 querySelectorAll
使用选择器表达式检索相关节点:
A simpler (albeit less efficient) approach is to use querySelectorAll
to retrieve the relevant nodes using a selector expression:
var divs = document.querySelectorAll('div.ui-controlgroup-controls > div')
这篇关于如何仅对元素的子元素运行getElementsByTagName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!