Get CSS path from Dom element(从 Dom 元素获取 CSS 路径)
问题描述
我得到了这个函数来获取一个 cssPath :
I got this function to get a cssPath :
var cssPath = function (el) {
var path = [];
while (
(el.nodeName.toLowerCase() != 'html') &&
(el = el.parentNode) &&
path.unshift(el.nodeName.toLowerCase() +
(el.id ? '#' + el.id : '') +
(el.className ? '.' + el.className.replace(/s+/g, ".") : ''))
);
return path.join(" > ");
}
console.log(cssPath(document.getElementsByTagName('a')[123]));
但我得到了这样的东西:
But i got something like this :
html > body > div#div-id > div.site > div.clearfix > ul.choices > li
但完全正确,它应该是这样的:
But to be totally right, it should look like this :
html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)
有人有什么想法可以简单地在 javascript 中实现它吗?
Did someone have any idea to implement it simply in javascript ?
推荐答案
要始终获得正确的元素,您需要使用 :nth-child()
或 :nth-of-type()
用于不唯一标识元素的选择器.所以试试这个:
To always get the right element, you will need to use :nth-child()
or :nth-of-type()
for selectors that do not uniquely identify an element. So try this:
var cssPath = function(el) {
if (!(el instanceof Element)) return;
var path = [];
while (el.nodeType === Node.ELEMENT_NODE) {
var selector = el.nodeName.toLowerCase();
if (el.id) {
selector += '#' + el.id;
} else {
var sib = el, nth = 1;
while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && nth++);
selector += ":nth-child("+nth+")";
}
path.unshift(selector);
el = el.parentNode;
}
return path.join(" > ");
}
您可以添加一个例程来检查其相应上下文中的唯一元素(如 TITLE
、BASE
、CAPTION
等).
You could add a routine to check for unique elements in their corresponding context (like TITLE
, BASE
, CAPTION
, etc.).
这篇关于从 Dom 元素获取 CSS 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Dom 元素获取 CSS 路径


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01