Get element's CSS selector (when it doesn'

2020-01-24 07:03发布

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?

6条回答
smile是对你的礼貌
2楼-- · 2020-01-24 07:23

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

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

> UTILS.cssPath(node)

For implementation example see css_path.js

查看更多
放我归山
3楼-- · 2020-01-24 07:23

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

you can use jquery's nth child() function.

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

example from 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.

查看更多
走好不送
4楼-- · 2020-01-24 07:31

Check this CSS selector generator library @medv/finder

  • Generates shortest selectors
  • Unique selectors per page
  • Stable and robust selectors
  • 2.9 kB gzip and minify size

Example of generated selector:

.blog > article:nth-child(3) .add-comment
查看更多
Evening l夕情丶
5楼-- · 2020-01-24 07:37
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.

查看更多
Bombasti
6楼-- · 2020-01-24 07:37

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

查看更多
够拽才男人
7楼-- · 2020-01-24 07:42

Use FireFox with FireBug installed.

  • Right-click any element
  • Select "Inspect Element"
  • Right click the element in the HTML tree
  • Select "Copy XPath" or "Copy CSS Path"

Output for the permalink to this answer (XPath):

/html/body/div[4]/div[2]/div[2]/div[2]/div[3]/table/tbody/tr/td[2]/table/tbody/tr/td/div/a

CSS Path:

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 ...

If that is your intent, there may be an easier way through 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.

查看更多
登录 后发表回答