获取仅标记ChildNodes不是TextNodes

时间:2015-10-09 18:28:57

标签: javascript

我已经用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>

因此,我想仅获取pimgaem个对象..

1 个答案:

答案 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>