简体   繁体   中英

Jquery - Get element location in the DOM

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM