Posted By

crutzdesigns on 02/04/11


Tagged

jqueryxpath


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

crypticsoft


jQuery().xpath


 / Published in: jQuery
 

Returns the xpath to selected element.

Usage: $("div#item1").xpath();

  1. jQuery.fn.extend({
  2. xpath: function(){
  3. path = new Array();
  4. for(var i in this){
  5. var elt = this[i];
  6.  
  7. if (elt && elt.id){
  8. path.push('//' + elt.tagName.toLowerCase() + '[id="' + elt.id + '"]');
  9.  
  10. } else {
  11. var tpath = "";
  12. for (; elt && elt.nodeType == 1; elt = elt.parentNode){
  13. idx = 1;
  14. for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
  15. if(sib.nodeType == 1 && sib.tagName == elt.tagName) idx++;
  16.  
  17. xname = elt.tagName.toLowerCase();
  18.  
  19. if (idx > 1)
  20. xname += "[" + idx + "]";
  21.  
  22. tpath = "/" + xname + tpath;
  23. }
  24. if(tpath.length > 0)
  25. path.push(tpath);
  26. }
  27. }
  28.  
  29. return path;
  30. }
  31. });

Report this snippet  

You need to login to post a comment.