views:

360

answers:

2

Looking for the best way to GET the xpath and css selector of a specific element using jQuery or Extjs. To basically select a random element and traverse up the dom and retreive it's unique css selector or xpath. Is there a function that can do this already or does anyone have a custom function that can do this?

A: 

There are an infinite number of selectors for any given element. What do you need it for? You might be able to use Firefox plugin like XPather?

troelskn
need to be able to execute a reverse lookup on it to select the element again using the xpath or css selector that was generated
Jalmarez
That I get. The questions is rather; If you have the element, why not simply store a reference to it? If you're doing web-scraping, why can't you use tools like XPather?
troelskn
+2  A: 

Why not just check for an "id" value, and if there is one there just use it. If there isn't one, generate a unique random "id" value, give it to the element, and then use that.

edit: here's a proof-of-concept jQuery hack to build up a selector for any element you click on.

$('*').unbind('click.m5').bind('click.m5', function(ev) {
  if (this != ev.target) return;

  var cn = function(elem) {
    var n = $(elem).parent().children().index(elem);
    return elem.tagName + ':nth-child(' + n + ')';
  };
  var selector = cn(this);
  $(this).parents().each(function() {
    if (/BODY|HTML/.test(this.tagName))
      selector = this.tagName + '>' + selector;
    else
      selector = cn(this) + '>' + selector;
  });
  console.log("Selector: " + selector);
  $(selector).css('background-color', 'red');
});
Pointy
Yes... but in the case of web scraping this would not work for return visits.
Jalmarez
Well that's true, though if you're web scraping a site you have no control over you may not be able to rely on any of the content being consistent anyway. In other words, the third child "span" of the fourth "div" under the first "div" after the second "h1" in the body may or may not be the same content you saw there last time.
Pointy
True, but it should work for a while until it is changed and needs to be updated. I'm thinking that the css selector might do better.
Jalmarez
Well then what would probably work best would be to build up a selector from the target element, adding pieces of the form "tag:nth-child(n)". I'll edit my answer with a proof-of-concept.
Pointy
Thats a good start... thanks
Jalmarez