开发者

Best way to GET the xpath and css selector of a specific element

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 t开发者_Go百科hat can do this already or does anyone have a custom function that can do this?


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');
});


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜