Pablo
Pablo

Reputation: 29519

DOM accessing element JS

Given the following xml

<rss>
    <channel>
    ...
    <pubDate>20/30/2099</pubDate>
    ...
    <item>
        ...
        <pubDate>10/30/2099</pubDate>
        ...
    </item>
    ...
    <item>
        ...
        <pubDate>40/30/2099</pubDate>
        ...
    </item>
    ...
    </channel>
</rss>

how would I efficiently access pudDate in channel and items as array, as well as pudDate in that array.

Upvotes: 0

Views: 88

Answers (1)

KooiInc
KooiInc

Reputation: 122906

You could use xpath (as long as you don't need it for IE), using document.evaluate. Here's the function I use for it:

 function getFromXPath(expression,rootEl){
   rootEl = rootEl || docbody;
   var ret = [] 
             ,xresult = document.evaluate(expression, rootEl, null,
                         XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null)
             ,result = xresult.iterateNext();
   while (result) {
     ret[ret.length]= result;
     result = xresult.iterateNext();
   }
   return ret;
}

Where in your case expression could be something like "//channel/pubdate|channel/item/pubdate" (for all pubdates in the tree) or "//chanel/items" (for all item elements in the tree), and rootEl being the (xml) document root.

This function returns an array containing the elements you requested by xpath-expression.

Upvotes: 1

Related Questions