I am trying to find the first parent div that has id attribute.
The selectors is 'div .img' and it could be inside any nested div
<div id='div1'>
<div id='div2'> first nested parent div
<div>second div
<img class='img' src='test.jpg'/>
</div>
</div>
<div> //this div has no id
<div>another div
<img class='img' src='cookie.jpg'/>
</div>
<div>
</div>
The selector
$('div.img')
should output
div2
div1
div2 shows first becasue div2 has id attribute and it is the parent of the test.img
div1 shows next becasue cookie is the second image and the first parent div that has div1 id
I have tried
if($('div .img').find('.img').closest('div').attr('id')){
console.log($('div.img').closest('div').attr('id'))
}
but it doesn’t work. Are there anyways to do this? Thanks so much!
OR using the class:
or
EDIT per comment to clarify use to ONLY find them once: