Skip to content

Instantly share code, notes, and snippets.

@starzonmyarmz
Forked from smith/js_dom.html
Created June 24, 2011 20:34
Show Gist options
  • Save starzonmyarmz/1045626 to your computer and use it in GitHub Desktop.
Save starzonmyarmz/1045626 to your computer and use it in GitHub Desktop.
Get DOM Structure from BODY to clicked element
<!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