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
Does getElementsByTagName return ALL child nodes?
提问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
, value
nodes OR just property
nodes with no children?
假设我们已将 XML 文档正确加载到变量中var xml
,是否xml.getElementsByTagName("property")
返回 ALL property
、label
、value
节点或只是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 label
or value
nodes, what's the best way to get that done?
如果函数不会返回任何label
或value
节点,那么完成它的最佳方法是什么?
回答by Jukka K. Korpela
The getElementsByTagName
method “Returns NodeList
of all descendantElements
with 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 labels
a (live) list of label
children of the first property
element in the document, provided that there is at least one property
element. (So for robustness, you might wish to check e.g. that props.length > 0
before proceeding to the second statement.)
做您似乎想做的事情:它分配给文档中第一个元素labels
的label
子property
元素的(实时)列表,前提是至少有一个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
}
}