如何使用javascript或jquery生成CSS路径? [英] how to generate CSS Path with javascript or jquery?

查看:76
本文介绍了如何使用javascript或jquery生成CSS路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关如何为元素生成CSS路径的任何建议吗?

Any suggestions for how to generate the CSS Path for an element?

CSS路径是识别特定元素所需的css选择器的路径,例如,如果我的HTML是:

A CSS path is the path of css selectors needed to identify a specific element, for example, if my html is:

<div id="foo">
 <div class="bar">
  <ul>
   <li>1</li>
   <li>2</li>
   <li><span class="selected">3</span></li>
  </ul>
 </div>
</div>

然后,3的类路径将是 div#foo div .bar ul li span.selected

then, the class path to "3" would be div#foo div.bar ul li span.selected

JQuery使用类路径来识别DOM元素并可能提供一个很好的解决方案,但我一直无法到目前为止找到一个。

JQuery uses class paths to identify DOM elements and might provide a good solution, but I've been unable to find one up until now.

推荐答案

我不明白为什么这个被投票,一个好的和合法的问题

i don't understand why this one is downvoted, a good and legitimate question

这是一个(过于简化的)示例,说明如何做到这一点

here's an (oversimplified) example on how this could be done

<div id="a">
    <div class="b">
        <div><span></span></div>
    </div>
</div>


<script>
function getPath(elem) {
    if(elem.id)
        return "#" + elem.id;
    if(elem.tagName == "BODY")
        return '';
    var path = getPath(elem.parentNode);
    if(elem.className)
        return path + " " + elem.tagName + "." + elem.className;
    return path + " " + elem.tagName;
}

window.onload = function() {
    alert(getPath(document.getElementsByTagName("SPAN")[0]));
}
</script>

这篇关于如何使用javascript或jquery生成CSS路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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