Start

Find the closest parent who has a class

Suppose we have the following markup:

<div class="hello"> <p> <a href="#"><span id="start">Start</span></a> </p> </div> 

Is there a way to find the closest element to $('#start') that has a class attribute, going up the dom tree?

CLARIFICATION: I really need to get a string containing the full path from $ ('# start') to $ (. Hello), which will contain the tag names for all elements, so far So, based on the markup above, it displays: " span a p .hello "

You can get the element tag name element.prop('tagName')

+4
source share
3 answers

If you need the closest element, including the one you started with, use .closest :

 $('#start').closest('[class]'); 

If you want to exclude the source element, use this:

 $('#start').parents('[class]').first(); 

To get the full matching path, try the following:

 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 does not provide AFAIK a simple method for selecting an element and each of its ancestors.

+8
source

What about

 $('#start').closest("[class]"); 
+10
source

You can get a string containing the parent names of a node until you come across one with the class using jQuery parents() : Demo

 var path = 'span '; $('#start').parents().each(function() { if($(this).is('[class]')) { path += '.' + this.className + ' '; return false; // break } else { path += this.nodeName + ' '; } }); console.log(path); 

Yes you can do:

 $('#start').closest("[class]"); 
+4
source

Source: https://habr.com/ru/post/1480953/


All Articles