我正在尝试查找第一个具有 id
属性的父 div
。
选择器是'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'))
}
但它不起作用。有办法做到这一点吗?非常感谢!
最佳答案
我建议:
var divsWithIDs = $('img.img').parents('div[id]').get();
console.log(divsWithIDs);
此方法查找 img.img
元素,然后查找这些图像的父级以查找具有 id
的 div
元素> 属性。 get()
方法将选择内容转换为数组。
引用文献:
关于javascript - 仅当父级 div 有 id 属性时才选择它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14697225/