从Dom元素获取CSS路径 [英] Get CSS path from Dom element

查看:408
本文介绍了从Dom元素获取CSS路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这个函数得到一个cssPath:

  var cssPath = function(el){
var path = [];

while(
(el.nodeName.toLowerCase()!='html')&&
(el = el.parentNode)&&
path.unshift .nodeName.toLowerCase()+
(el.id?'#'+ el.id:'')+
(el.className?'。'+ el.className.replace(/ \ s + / g,。):''))
);
return path.join(>);
}
console.log(cssPath(document.getElementsByTagName('a')[123]));

但我有这样的:

 html> body> div#div-id> div.site> div.clearfix> ul.choices> li 

但完全正确,它应该看起来像这样:

 html> body> div#div-id> div.site:nth-child(1)> div.clearfix> ul.choices> li:nth-​​child 



有人想在JavaScript中实现它吗?

解决方案

要始终获得正确的元素,您需要使用:nth-​​child():nth- of-type()用于不唯一标识元素的选择器。所以试试这个:

  var cssPath = function(el){
if(! ;
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 等) / p>

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)

Did someone have any idea to implement it simply in javascript ?

解决方案

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

You could add a routine to check for unique elements in their corresponding context (like TITLE, BASE, CAPTION, etc.).

这篇关于从Dom元素获取CSS路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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