Reputation: 14270
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!
Upvotes: 0
Views: 638
Reputation: 21482
You can use:
var $divsWithIds = $('img.img').closest('div[id]');
This is the same as the answer by @David Thomas, except using closest
instead of parents
. It selects all "img" elements with the ".img" class, and then gets the closest parent for each one.
In the following situation, using parents()
will include both "div1" and "div2", whereas using closest()
will return only 'div2':
<div id='div1'>
<div id='div2'>
<div>
<img id="img1" class='img' src='test.jpg'/>
</div>
</div>
</div>
<div>
<img id="img2" class='img' src='cookie.jpg'/>
<div>
Upvotes: 1
Reputation: 34196
var IamadivparentandhaveanId=$('div').find('img').closest('div[id]');
OR using the class:
$('div').find('img.img').closest('div[id]');
or
$('.img').closest('div[id]');
EDIT per comment to clarify use to ONLY find them once:
$('img.img').each(function(){
$(this).closest('div[id]');
});// or use .filter if that is perferred
Upvotes: 1
Reputation: 116
You can use jQuery each to iterate over the parents.
$('div img').each(function (a, b) {
var x = $(b).parent();
while (x && !x.attr('id')) {
x = x.parent();
}
console.log(x.attr('id'));
});
Upvotes: 0
Reputation: 253396
I'd suggest:
var divsWithIDs = $('img.img').parents('div[id]').get();
console.log(divsWithIDs);
This approach looks for the img.img
element, then looks through the parents of those images to find those div
elements that have an id
attribute. The get()
method converts the selection to an array.
References:
Upvotes: 3