25

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

Phil C
  • 3,687
  • 4
  • 29
  • 51
mike
  • 283
  • 1
  • 4
  • 8

3 Answers3

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