DISQUS

Blog of Jeff: “Brief” Guide to JavaScript – Part 5

  • ppds · 2 months ago
    Your explanation is clear. However, a very efficient way to play with DOM in Javascript (and other languages for that matter is to use XPath). Here is a sample code to go trough all link nodes inside the dom document and do something with them:

    var findPattern = "//a"; // This is the xpath pattern. You can use more powerful xpathes
    var resultLinks = document.evaluate( findPattern, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );

    var i=0;
    while ( (res = resultLinks.snapshotItem(i) ) !=null ){
    //do something to the link
    i += 1;
    }
  • jeffhui · 2 months ago
    Thanks. Covering XPath is definitely a better option; I always had a sense of ignorance that XPath wasn't consistent.

    For people that are interested, most javascript frameworks actually utilize XPath for selectors. XPath is a browser-supported implementation for traversing XML-trees, like HTML.