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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4588119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:06:17  来源:igfitidea点击:

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

javascriptdomcss-selectors

提问by rcphq

I'm trying to modify a page through JavaScript/CSS (much like Stylish or Greasemonkey do). 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). How can I achieve this?

我正在尝试通过 JavaScript/CSS 修改页面(很像 Stylish 或 Greasemonkey 所做的)。这是一个非常复杂的页面(我没有构建,或者无法修改预渲染),这使得构建 CSS 选择器变得困难(手动查看文档结构)。我怎样才能做到这一点?

采纳答案by Sean Patrick Floyd

Use FireFox with FireBug installed.

使用安装了 FireBug 的 FireFox。

  • Right-click any element
  • Select "Inspect Element"
  • Right click the element in the HTML tree
  • Select "Copy XPath" or "Copy CSS Path"
  • 右键单击任何元素
  • 选择“检查元素”
  • 右键单击 HTML 树中的元素
  • 选择“复制 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/body/div[4]/div[2]/div[2]/div[2]/div[3]/table/tbody/tr/td[2]/table/tbody/tr/td/div /一种

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.

对于不同的浏览器,最后一行可能需要以不同的方式实现。没有测试。

回答by Phrogz

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-childinstead of CSS classes to properly disambiguate for a single child.

编辑:更改代码以使用nth-child而不是 CSS 类来正确消除单个孩子的歧义。

回答by tutuDajuju

I found I could actually use this code from chrome devtools sourceto solve this, without that many modifications.

我发现我实际上可以使用来自 chrome devtools 源的这段代码来解决这个问题,而无需进行那么多修改。

After adding relevant methods from WebInspector.DOMPresentationUtilsto new namespace, and fixing some differences, I simply call it like so:

WebInspector.DOMPresentationUtils从新命名空间添加相关方法并修复一些差异后,我简单地这样称呼它:

> UTILS.cssPath(node)

For implementation examplesee css_path.js

实现示例css_path.js

回答by Anton Medvedev

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

回答by Yassine

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(" > ");
}

回答by andrewk

you can use for css first-child pseudo classes if the element is a first child in a div table or body..etc

如果元素是 div 表或正文中的第一个子元素,则可以将其用于 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 美分。