[英]How can I select outermost tag which contains img as direct child
I have following markup 我有以下标记
var divs = $('div:has(img)').not(':parent:has(>img)'); divs.css('border','1px solid red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div><!-- get this div --> 1 <img alt='#' /> <div> 2 <img alt='#' /> <div> 3 <img alt='#' /> <div> 4 <img alt='#' /> </div> </div> </div> </div> <div><!-- get this div --> 5 <img alt='#' /> <div> 6 <img alt='#' /> </div> <div> 7 <img alt='#' /> </div> </div> <div> <div><!-- get this div --> 8 <img alt='#' /> </div> </div>
From this I need to select the outermost div which contains img tag, that I don't want to select div if it's parent contains img
tag as direct child. 从这里,我需要选择包含img标签的最外面的div,如果它的父级包含
img
标签作为直接子元素,则我不想选择div。 I have tried var divs = $('div:has(img)').not(':parent:has(>img)');
我试过了
var divs = $('div:has(img)').not(':parent:has(>img)');
but it only works when it's have a parent. 但只有在有父母的情况下才有效。
Your main problem is the fact that :parent
selector does not do what you think it does. 您的主要问题是
:parent
选择器没有执行您认为的操作。 CSS rules never go upwards. CSS规则永远不会向上。 So if you need to go upwards, you need to do this using JavaScript (using the function
.parent()
, which does not have an equivalent in CSS selectors, not even jQuery extended ones). 因此,如果需要向上使用,则需要使用JavaScript(使用
.parent()
函数,它在CSS选择器中没有等效项,甚至没有jQuery扩展选择器)。
var divs = $('div:has(>img)').filter(function(i, n) { return !($(n).parent().children('img').length); });
divs.css('color','red');
However, this will paint everything red, because of the first C in CSS ("cascading"): the declaration of colour red on 1, 5 and 8 will paint all text inside those divs red. 但是,由于CSS中的第一个C(“级联”),这会将所有内容涂成红色:在1、5和8上声明红色,会将div中的所有文本涂成红色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.