-
-
Save starzonmyarmz/1045626 to your computer and use it in GitHub Desktop.
Get DOM Structure from BODY to clicked element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<!--[if lt IE 9]> | |
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
<style> | |
* { | |
cursor: pointer; | |
} | |
span { | |
display: block; | |
border-bottom: 1px solid #000; | |
} | |
</style> | |
</head> | |
<body> | |
<div> | |
<section id="hello"> | |
<h1>Hi There!</h1> | |
</section> | |
<section> | |
<div> | |
<p>This is a test paragraph</p> | |
</div> | |
<span>Test #1</span> | |
<span>Test #2</span> | |
<span>Test #3</span> | |
<span>Test #4</span> | |
</section> | |
</div> | |
<!-- Uncomment the following line to include jQuery from Google --> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> | |
<script> | |
$("*").bind("click", function (event) { | |
var t = $(this), | |
n = t[0].nodeName, // current node name | |
dir = [n], // list of nodes | |
str; // string representation | |
// Loop through nodes to get the DOM | |
// structure to the clicked node | |
while (n[0].nodeName !== "BODY") { | |
n = t.prev(); | |
if (n.length > 0) { | |
// Element is a sibling node | |
str = n[0].nodeName + " +"; | |
} else { | |
// Element is a parent node | |
n = t.parent(); | |
str = n[0].nodeName + " >"; | |
} | |
dir.unshift(str); | |
t = n; | |
} | |
// Convert the array to a string to be used as a selector | |
dir = dir.join(" "); | |
$(dir).css("background", "yellow"); | |
return false; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment