Search code examples
javascriptxmldocumentdomparser

Javascript: XMLDocument iteration


I have the following code:

var xmlString = ajaxRequest.responseText.toString();
parser = new DOMParser()
doc = parser.parseFromString(xmlString, "text/xml");

The response text is a complete HTML document. After I create the XMLDocument (doc), I want to go over each node, manipulate some stuff and print it.

How can I iterate the XMLDocument? I want to go on each one of its nodes.

Thanks!


Solution

  • A little example if you want to get all links from this XML and print their text

    var links = doc.documentElement.getElementsByTagName("a");
    
    for (i=0;i<links.length;i++)  {  
        var txt=links[i].firstChild.nodeValue;
        document.write(txt + '<br>');
    }
    

    Almost sure that this is correct, didn't had time to test it.

    You may read this articles to go deeper:

    getElementsByTagName

    nodeName

    NodeList

    Hope this helps.

    Best regards!