Page 1
Getting an XML representation of the current HTML document
Page 2
Index
See this article in english  Ver este artículo en español 
Page 3
Obtener la posición absoluta de cualquier elemento HTML

Browser independant XPath evaluation

Alexander Hristov

I recently had to write for an AJAX app a function to evaluate an arbitrary XPath expression and to retrieve the resulting list of nodes in a browser independant way..Mozilla (Firefox), Opera et al implement the DOM XPath standard, while Internet Explorer as always does it in its own way (IE was,however, the first browser AFAIK that had this feature built-in, before the standard even existed) The problem is that not only the funcion names are different in the different browsers, but the returned objects are different, too.

Finally the solution was to create a wrapper function that evaluates the expression and returns a custom-built object that implements the iteration method differently depending on the browser:

xpath.js
 
function selectXPath(expr, node) {
  if (document.evaluate) {
    return {
      list : node.evaluate(expr,node,null,XPathResult.ANY_TYPE,null),
      next : function() { 
        return this.list.iterateNext()
      }
    }
  } else {
    return {
      list: node.selectNodes(expr),
      i : 0,
      next: function() {
        if (this.i > this.list.length)
          return null;
        return this.list[this.i++];
      }
    }
  }
}


 

The function first checks if we have a DOM XPath implementation and if so, it uses it. If we don't have one, the functiona assumes the browser is IE and uses the selectNodes() function. In both cases the result is an object that has a single next() method for retrieving the nodes from the resulting list.

An example usage could be:

 
function test() {
  var imagenes="Images in this document: ";
  if  (document.evaluate)
    var result = selectXPath("//IMG",document);
  else
    var result = selectXPath("//IMG",document2DOM());
  var nodo;
  do {
    nodo = result.next();
    if (nodo)  imagenes += nodo.getAttribute("src") + "\n";
  } while (nodo);
  alert(imagenes);
}

 
( the document2DOM() function is the one describe in the previous tip )

Press   to test this function on this document



Source code



 

Comments

 

Add a Comment

Name (optional)
EMail (optional, will not be displayed)

Text