HTML
<body>
<div class="lol">
<a class="rightArrow" href="javascriptVoid:(0);" title"Next image">
</div>
</body>
Pseudo Code
$(".rightArrow").click(function() {
rightArrowParents = this.dom(); //.dom(); is the pseudo function ... it should show the whole
alert(rightArrowParents);
});
Alert message would be:
body div.lol a.rightArrow
How can I get this with javascript/jquery?
Using jQuery, like this (followed by a solution that doesn’t use jQuery except for the event; lots fewer function calls, if that’s important):
Live example:
(In the live examples, I’ve updated the
classattribute on thedivto belol multito demonstrate handling multiple classes.)That uses
parentsto get the ancestors of the element that was clicked, removes thehtmlelement from that vianot(since you started atbody), then loops through creating entries for each parent and pushing them on an array. Then we useaddBackto add theaback into the set, which also changes the order of the set to what you wanted (parentsis special, it gives you the parents in the reverse of the order you wanted, but thenaddBackputs it back in DOM order). Then it usesArray#jointo create the space-delimited string.When creating the entry, we trim
className(since leading and trailing spaces are preserved, but meaningless, in theclassattribute), and then if there’s anything left we replace any series of one or more spaces with a.to support elements that have more than one class (<p class='foo bar'>hasclassName="foo bar", so that entry ends up beingp.foo.bar).Just for completeness, this is one of those places where jQuery may be overkill, you can readily do this just by walking up the DOM:
Live example:
There we just use the standard
parentNodeproperty (or we could useparentElement) of the element repeatedly to walk up the tree until either we run out of parents or we see thehtmlelement. Then we reverse our array (since it’s backward to the output you wanted), and join it, and we’re good to go.