简体   繁体   English

获取元素的CSS选择器(当它没有id时)

[英]Get element's CSS selector (when it doesn't have an id)

I'm trying to modify a page through JavaScript/CSS (much like Stylish or Greasemonkey do). 我正在尝试通过JavaScript / CSS修改页面(很像Stylish或Greasemonkey)。 This is a very complex page (that I didn't build, or can't modify pre-render), which makes constructing the CSS selector hard to do (manually looking at document structure). 这是一个非常复杂的页面(我没有构建,或者无法修改预渲染),这使得构建CSS选择器很难做到(手动查看文档结构)。 How can I achieve this? 我怎样才能做到这一点?

function fullPath(el){
  var names = [];
  while (el.parentNode){
    if (el.id){
      names.unshift('#'+el.id);
      break;
    }else{
      if (el==el.ownerDocument.documentElement) names.unshift(el.tagName);
      else{
        for (var c=1,e=el;e.previousElementSibling;e=e.previousElementSibling,c++);
        names.unshift(el.tagName+":nth-child("+c+")");
      }
      el=el.parentNode;
    }
  }
  return names.join(" > ");
}

console.log(  fullPath( $('input')[0] ) );
// "#search > DIV:nth-child(1) > INPUT:nth-child(1)"

This seems to be what you are asking for , but you may realize that this is not guaranteed to uniquely identify only one element. 这似乎是你要求的 ,但你可能会意识到这并不能保证只能唯一地识别一个元素。 (For the above example, all the sibling inputs would be matched as well.) (对于上面的示例,所有兄弟输入也将匹配。)

Edit : Changed code to use nth-child instead of CSS classes to properly disambiguate for a single child. 编辑 :更改代码以使用nth-child而不是CSS类来正确消除单个子项的歧义。

Use FireFox with FireBug installed. 使用安装了FireBug的FireFox。

  • Right-click any element 右键单击任何元素
  • Select "Inspect Element" 选择“检查元素”
  • Right click the element in the HTML tree 右键单击HTML树中的元素
  • Select "Copy XPath" or "Copy CSS Path" 选择“复制XPath”或“复制CSS路径”

Output for the permalink to this answer (XPath): 此答案的永久链接输出(XPath):

/html/body/div[4]/div[2]/div[2]/div[2]/div[3]/table/tbody/tr/td[2]/table/tbody/tr/td/div/a / HTML /体/格[4] / DIV [2] / DIV [2] / DIV [2] / DIV [3] /表/ tbody的/ TR / TD [2] /表/ tbody的/ TR / TD /格/一个

CSS Path: CSS路径:

html body.question-page div.container div#content div#mainbar div#answers div#answer-4588287.answer table tbody tr td table.fw tbody tr td.vt div.post-menu a html body.question-page div.container div #content div#mainbar div#answers div#answer-4588287.answer table tbody tr td table.fw tbody tr td.vt div.post-menu a


But regarding this comment: 但关于这个评论:

my final intent is to create a css selector for the object ... 我的最终目的是为对象创建一个css选择器...

If that is your intent, there may be an easier way through JavaScript: 如果这是您的意图,可能有一种更简单的方法通过JavaScript:

var uniquePrefix = 'isThisUniqueEnough_';
var counterIndex = 0;
function addCssToElement(elem, cssText){
    var domId;
    if(elem.id)domId=elem.id;
    else{
        domId = uniquePrefix + (++counterIndex);
        elem.id = domId;
    }
    document.styleSheets[0].insertRule("#"+domId+"{"+cssText+"}");
}

The last line may need to be implemented differently for different browsers. 对于不同的浏览器,可能需要以不同的方式实现最后一行。 Did not test. 没试过。

I found I could actually use this code from chrome devtools source to solve this, without that many modifications. 我发现我实际上可以使用chrome devtools源代码来解决这个问题,而不需要那么多修改。

After adding relevant methods from WebInspector.DOMPresentationUtils to new namespace, and fixing some differences, I simply call it like so: 在将WebInspector.DOMPresentationUtils相关方法添加到新命名空间并修复一些差异后,我只需将其称为:

> UTILS.cssPath(node)

For implementation example see css_path.js 有关实现示例, 请参阅css_path.js

Check this CSS selector generator library @medv/finder 检查这个CSS选择器生成器库@ medv / finder

  • Generates shortest selectors 生成最短的选择器
  • Unique selectors per page 每页唯一选择器
  • Stable and robust selectors 稳定而强大的选择器
  • 2.9 kB gzip and minify size 2.9 kB gzip和缩小大小

Example of generated selector: 生成的选择器示例:

.blog > article:nth-child(3) .add-comment

you can use for css first-child pseudo classes if the element is a first child in a div table or body..etc 如果元素是div表或body..etc中的第一个子元素,则可以使用css first-child伪类

you can use jquery's nth child() function. 你可以使用jquery的第n个child()函数。

http://api.jquery.com/nth-child-selector/ http://api.jquery.com/nth-child-selector/

example from jquery.com 来自jquery.com的例子

<!DOCTYPE html>
<html>
<head>
  <style>

  div { float:left; }
  span { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
  <div><ul>
    <li>John</li>
    <li>Karl</li>
    <li>Brandon</li>

  </ul></div>
  <div><ul>
    <li>Sam</li>
  </ul></div>

  <div><ul>
    <li>Glen</li>
    <li>Tane</li>
    <li>Ralph</li>

    <li>David</li>
  </ul></div>
<script>$("ul li:nth-child(2)").append("<span> - 2nd!</span>");</script>

</body>
</html>

my 2 cents if I understood the question correctly. 如果我正确地理解了这个问题我的2美分。

 function getCssSelector(el) { names = []; do { index = 0; var cursorElement = el; while (cursorElement !== null) { ++index; cursorElement = cursorElement.previousElementSibling; }; names.unshift(el.tagName + ":nth-child(" + index + ")"); el = el.parentElement; } while (el !== null); return names.join(" > "); } 

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

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