How would you write the Jquery to get the closest div that actually has an ID defined?
Asked
Active
Viewed 5.9k times
25
-
3Define 'closest' in more detail. Child, sibling or parent? – Martijn Pieters Feb 23 '11 at 19:40
-
I imagine that even with the `closest` method being available, the answer to this would be at least 50-100 lines of code if you want to search siblings and children as well. – mVChr Feb 23 '11 at 19:48
-
sorry, i wanted a parent that is a div and has and id – mike Feb 23 '11 at 19:50
3 Answers
45
You should use has attribute selector. This sample should do the work:
$('selector').closest('[id]')

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

gor
- 11,498
- 5
- 36
- 42
-
3This looks to ancestors only. If he wants a sibling or child that's closest as well this won't be enough. – mVChr Feb 23 '11 at 19:43
-
-
7
14
$(elementToStart).parent().closest('div[id]');
I use the parent() to avoid just getting the element itself.
Example: http://jsfiddle.net/zQRFT/1/

AlfaTeK
- 7,487
- 14
- 49
- 90
-
-
parent().closest() is the same as using parents() which begins with the parent element – Mosaaleb Feb 01 '22 at 15:22
11
Look for an id attribute on a div, using the closest method:
$(this).closest('div[id]');
The [id]
brackets there is what's called the Has Attribute Selector

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343