我已经用JavaScript编程了一段时间,但今天我只知道element.childNodes
返回包含文本的节点数组!!!
我可能从来没有遇到麻烦,因为我曾经创建过元素并在段落中附加文字;但是现在我想到了,作为节点的文本可能会变得非常混乱!
我的问题是:我怎样才能获得标签而非文本节点的子节点。
例如:
<div id="e">
I don't want to include this text right here.
<p>I want to get this paragraph child</p>
I also want to <em>exclude</em> this text...
<img src="image.jpg" alt=" " />
<a href="google.com">Google</a>
Exclude this text too..
</div>
因此,我想仅获取p
,img
,a
和em
个对象..
答案 0 :(得分:0)
以下是使用.children
仅定位元素的简单示例。 childNodes
默认返回textNodes,有时非常有用,但不适合您的示例用法。
[].forEach.call(document.querySelector('#e').children,function(el){ el.style.color = 'red'; });
<div id="e">
I don't want to include this text right here.
<p>I want to get this paragraph child</p>
I also want to <em>exclude</em> this text...
<img src="image.jpg" alt=" " />
<a href="google.com">Google</a>
Exclude this text too..
</div>