Assume we have the following markup:
<div class="hello">
<p>
<a href="#"><span id="start">Start</span></a>
</p>
</div>
Is there any way to find the closest element to $('#start')
which has a class attribute, going up the dom tree?
CLARIFICATION: I actually need to get a string containing the complete path from $('#start') to $(.hello), which would contain the tag names of all elements until the So based on the markup above - it would output: 'span a p .hello'
You can get the elements tag name with element.prop('tagName')
What about
$('#start').closest("[class]");
If you want the closest element, including the one you started with, use .closest
:
$('#start').closest('[class]');
If you want to exclude the starting element, use this:
$('#start').parents('[class]').first();
To get the full matching path, try this:
var path = [];
var el = document.getElementById('start');
while (el) {
if (el.className) {
path.push('.' + el.className);
break;
} else {
path.push(el.tagName);
}
el = el.parentNode;
}
var ancestors = path.join(' ');
See http://jsfiddle.net/alnitak/EZWNR/
I used native JS because jQuery doesn't AFAIK provide a simple method to select an element and every one of its ancestors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With