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?