25

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

3
  • 3
    Define 'closest' in more detail. Child, sibling or parent? Commented Feb 23, 2011 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
    Commented Feb 23, 2011 at 19:48
  • sorry, i wanted a parent that is a div and has and id
    – mike
    Commented Feb 23, 2011 at 19:50

3 Answers 3

45

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

$('selector').closest('[id]')
3
  • 3
    This looks to ancestors only. If he wants a sibling or child that's closest as well this won't be enough.
    – mVChr
    Commented Feb 23, 2011 at 19:43
  • how does this give me divs with ids as opposed that anything with an id?
    – mike
    Commented Feb 23, 2011 at 19:51
  • 7
    Don't you mean .closest('div[id]')?
    – gen_Eric
    Commented Feb 23, 2011 at 19:59
14
$(elementToStart).parent().closest('div[id]');

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

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

2
  • this should be the answer, without using parent() mine was not working
    – Harry
    Commented Jul 29, 2014 at 5:00
  • parent().closest() is the same as using parents() which begins with the parent element
    – Mosaaleb
    Commented Feb 1, 2022 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.