javascript getElementsByTagName 是否返回所有子节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18820745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:20:04  来源:igfitidea点击:

Does getElementsByTagName return ALL child nodes?

javascripthtmlxmldom

提问by geoff

So let's say we have the following XML structure:

假设我们有以下 XML 结构:

<property>
    <label>Label 1</label>
    <value>value 1</label>
</property>
<property>
    <label>Label 2</label>
    <value>value 2</label>
</property>
<!-- more of these -->

Provided that we have correctly loaded the XML document into variable var xml, does xml.getElementsByTagName("property")return ALL property, label, valuenodes OR just propertynodes with no children?

假设我们已将 XML 文档正确加载到变量中var xml,是否xml.getElementsByTagName("property")返回 ALL propertylabelvalue节点或只是property没有子节点的节点?

Why I'm asking this is, I'd like to be able to do the following:

为什么我要问这个,我希望能够做到以下几点:

var props = xml.getElementsByTagName("property");
var labels = props[0].getElementsByTagName("label");

If the function will not return any labelor valuenodes, what's the best way to get that done?

如果函数不会返回任何labelvalue节点,那么完成它的最佳方法是什么?

回答by Jukka K. Korpela

The getElementsByTagNamemethod “Returns NodeListof all descendantElementswith a given tag name”. So getElementsByTagName("property")returns all children, children of children, etc., that have the tag name property, no matter what the content of such a node is. It does not of course return any node with some different tag name.

getElementsByTagName方法“返回NodeList所有的后代Elements具有给定标记名称”。因此,无论此类节点的内容是什么getElementsByTagName("property"),都将返回所有具有标记 nameproperty的子节点、子节点的子节点等。它当然不会返回任何具有不同标签名称的节点。

So yes, the code

所以是的,代码

var props = xml.getElementsByTagName("property");
var labels = props[0].getElementsByTagName("label");

does what you seem to want to do: it assigns to labelsa (live) list of labelchildren of the first propertyelement in the document, provided that there is at least one propertyelement. (So for robustness, you might wish to check e.g. that props.length > 0before proceeding to the second statement.)

做您似乎想做的事情:它分配给文档中第一个元素labelslabelproperty元素的(实时)列表,前提是至少有一个property元素。(因此,为了稳健性,您可能希望props.length > 0在继续第二个语句之前检查一下。)

回答by S. S. Rawat

Try this, this is help you

试试这个,这对你有帮助

var props = xml.getElementsByTagName("property");
var eleChild = props .childNodes;
for( i = 0 , j = eleChild.length; i < j ; i++ ){
    if( eleChild[ i ].className == "autodropdown" ){
        YOUr_SCRIPT
    }
}