获取元素的CSS选择器(当它没有id) [英] Get element's CSS selector (when it doesn't have an id)

查看:237
本文介绍了获取元素的CSS选择器(当它没有id)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过JavaScript / CSS修改页面(很像时尚或Greasemonkey)。这是一个非常复杂的页面(我没有构建,或者不能修改预渲染),这使得构建CSS选择器很难做(手动查看文档结构)。如何实现这一点?

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?

推荐答案

使用FireFox安装FireBug。

Use FireFox with FireBug installed.


  • 右键单击任何元素

  • 选择检查元素

  • 右键单击HTML树中的元素

  • 选择复制XPath或复制CSS路径

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

answer(XPath):

Output for the permalink to this answer (XPath):


/ html / body / div [4] / 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/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

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:


我最终的目的是为对象创建一个css
选择器...

my final intent is to create a css selector for the object ...

如果这是您的意图,可能会有一种更简单的JavaScript方法:

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.

这篇关于获取元素的CSS选择器(当它没有id)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆