0

I'm trying to retrieve an elements location within the DOM when it's clicked. So that it could be used to generate on the fly styling for a selected element in a preview pane.

For instance assuming I have an onclick function running on every element in the page, when an element is clicked I want to have a value such as:

    div#a > ul.list > li:nth-child(3) > span

If a user clicked on the third span in the page below:

<html>
<body>
    <div id="a">
        <ul class="list">
            <li><span>first</span></li>
            <li><span>second</span></li>
            <li><span>third</span></li>
            <li><span>fourth</span></li>
        </ul>
    </div>
</body>
</html>

I've searched the web and tried a few old functions that were lying around but none seem to work.

I could use some code like below, and then loop through every parent until I hit body but this seems excessive.

$( "body *" ).click(function() {
    //retrieve current element information
    //retrieve tag name
    var tag = $(this).prop("nodeName");
    //retrieve id list
    var ids = $(this).prop("id");
    //replace whitespace with hash
    var ids = ids.replace(/\s/g, "#");
    //retrieve class list
    var classes = $(this).attr("class");
    //replace whitespace with point
    var classes = classes.replace(/\s/g, ".");
    //add ids and classes to tag name
    var current_element = tag + "#" + ids + "." + classes;
});

Are there any better ways?

Alex
  • 1,018
  • 1
  • 11
  • 21
  • 1
    I don't see faster than looping through every parent. You could use [elementsFromPoint](https://developer.mozilla.org/en-US/docs/Web/API/Document/elementsFromPoint) but it is not yet supported by every browsers out there (safari I am looking at you), and I do think it may actually be slower. – Quentin Roy May 05 '16 at 12:57
  • Possible duplicate of https://stackoverflow.com/questions/4588119/get-elements-css-selector-when-it-doesnt-have-an-id – flatline May 05 '16 at 13:04
  • Possible Dupe: http://stackoverflow.com/questions/5706837/get-unique-selector-of-element-in-jquery – Riddell May 05 '16 at 13:05

1 Answers1

1

its simple using while(...parentNode)

 var element = document.getElementById('elem');

    element.onclick=function(){
    var elem = this,
        elemPath = '';

    while(elem.parentNode){
       elemPath += elem.tagName +' > ';  
       elem = elem.parentNode;
    }
    alert(elemPath);
    }

i hope it helps

Marwan
  • 2,362
  • 1
  • 20
  • 35