JQuery: Closest div that has an ID
Asked Answered
M

3

25

How would you write the Jquery to get the closest div that actually has an ID defined?

Marbling answered 23/2, 2011 at 19:36 Comment(3)
Define 'closest' in more detail. Child, sibling or parent?Pharyngitis
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.Lepus
sorry, i wanted a parent that is a div and has and idMarbling
G
45

You should use has attribute selector. This sample should do the work:

$('selector').closest('[id]')
Grooms answered 23/2, 2011 at 19:40 Comment(3)
This looks to ancestors only. If he wants a sibling or child that's closest as well this won't be enough.Lepus
how does this give me divs with ids as opposed that anything with an id?Marbling
Don't you mean .closest('div[id]')?Septuplet
H
14
$(elementToStart).parent().closest('div[id]');

I use the parent() to avoid just getting the element itself.

Example: http://jsfiddle.net/zQRFT/1/

Haemoglobin answered 23/2, 2011 at 19:46 Comment(2)
this should be the answer, without using parent() mine was not workingShe
parent().closest() is the same as using parents() which begins with the parent elementSirreverence
P
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

Pharyngitis answered 23/2, 2011 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.