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.
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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With