Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate CSS Path with javascript or jquery?

Tags:

javascript

css

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

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>

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

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.

like image 619
dingdingding Avatar asked Oct 30 '09 07:10

dingdingding


1 Answers

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>
like image 101
user187291 Avatar answered Oct 11 '22 13:10

user187291