0
<div id="findThisId"></div>

<div id="divID">
    <span id="spanID">
        <p id="pID">p</p>
    </span>
</div>
<br/>
<div id="output"></div>

I've been able to get to the parent div of the <p> with this:

$('#pID').parent().parent().attr('id')

but how do then find the previous div id?

http://jsfiddle.net/W5NHH/

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
Norse
  • 5,674
  • 16
  • 50
  • 86

3 Answers3

4

This should work for you

$('#pID').closest('div').prev().attr('id');
Brian Noah
  • 2,962
  • 18
  • 27
2

All you need to do is insert a simple .prev():

$('#output').html($('#pID').parent().parent().prev().attr('id'));​

See the docs for .prev()

A common pitfall with using .prev() is that it is really only looking for direct siblings, so one might end up using .prevAll() in real world situations.

m90
  • 11,434
  • 13
  • 62
  • 112
  • Me too :) Just wanted to add this as it isn't 100% clear from the name of the method that it will just look for the next sibling. Been hearing of people going nuts because of this... – m90 Oct 14 '12 at 09:19
  • Interesting. I'll make sure to point this out to the juniors. – Brian Noah Oct 14 '12 at 09:24
  • The *trouble* starts when you use it with a selector write sth like `$(this).prev('div')` which pretty much feels like "Could I get the previous div please, thanks!" – m90 Oct 15 '12 at 07:38
1

Joining the party bit late but lil diff here :) http://jsfiddle.net/DF8jK/1/

Parents API - http://api.jquery.com/parents/

Hope it fits the cause as well. :)

This might come handy - jQuery: finding previous div

code

alert($('#pID').parents('div').prev().html());​
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77