获取元素的 CSS 选择器(当它没有 id 时) [英] Get element's CSS selector (when it doesn't have an id)
问题描述
我正在尝试通过 JavaScript/CSS 修改页面(很像 Stylish 或 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?
推荐答案
在安装了 FireBug 的情况下使用 FireFox.
Use FireFox with FireBug installed.
- 右键单击任何元素
- 选择检查元素"
- 右键单击 HTML 树中的元素
- 选择复制 XPath"或复制 CSS 路径"
此答案的永久链接 (XPath) 的输出:
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
/html/body/div[4]/div[2]/div[2]/div[2]/div[3]/table/tbody/tr/td[2]/table/tbody/tr/td/div/a
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:
我的最终目的是创建一个 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屋!