Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the nearest parent which has class

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')

like image 634
YemSalat Avatar asked Nov 29 '22 01:11

YemSalat


2 Answers

What about

$('#start').closest("[class]");
like image 177
tymeJV Avatar answered Dec 01 '22 14:12

tymeJV


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.

like image 34
Alnitak Avatar answered Dec 01 '22 16:12

Alnitak