简体   繁体   English

获取特定元素的xpath和CSS选择器的最佳方法

[英]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. 寻找使用jQuery或Extjs来获取特定元素的xpath和CSS选择器的最佳方法。 To basically select a random element and traverse up the dom and retreive it's unique css selector or xpath. 要基本上选择一个随机元素并遍历dom并返回,它是唯一的CSS选择器或xpath。 Is there a function that 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. 为什么不只检查一个“ id”值,如果有,就使用它。 If there isn't one, generate a unique random "id" value, give it to the element, and then use that. 如果没有,则生成一个唯一的随机“ id”值,将其提供给元素,然后使用该值。

edit: here's a proof-of-concept jQuery hack to build up a selector for any element you click on. 编辑:这是一个概念验证jQuery hack,可为您单击的任何元素建立选择器。

$('*').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 ? 您也许可以使用XPather之类的Firefox插件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM