如何使用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>