我正在尝试找到第一个div
具有id
属性的父级。
选择器是'div .img'
,它可以在任何嵌套的 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>
选择器
$('div.img')
应该输出
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
我试过了
if($('div .img').find('.img').closest('div').attr('id')){
console.log($('div.img').closest('div').attr('id'))
}
但它不起作用。有没有办法做到这一点?非常感谢!