Does getElementsByTagName return ALL child nodes?

14,537

Solution 1

The getElementsByTagName method “Returns NodeList of all descendant Elements 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.

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.)

Solution 2

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
    }
}
Share:
14,537
geoff
Author by

geoff

Updated on June 18, 2022

Comments

  • geoff
    geoff almost 2 years

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

    <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?

    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?