I would like to find all the elements that match the selector, but not if it is already contained in the corresponding element.
$('#container').find('.child').not('.child .child');
Note that .child elements do not need direct descendants.
why doesn't it work?
I would like to highlight the entire element that appears in $('#container').find('.child'), but exclude / filter()any that will be here $('#container').find('.child .child'), because one of its ancestors is.child
var children = $('#container').find('.child').filter(function (i, el) {
return !$(el).closest('.child').length;
});
for some reason this does not work either JSFIDDLE
snippet adapted from @RonenCypis answer
var selector = ' .child ';
var children = $('#container').find(selector).filter(function(i, el) {
return !$(el).closest(selector).length;
});
children.css('background-color', 'blue');
#container div {
float: left;
display: inline-block;
width: 50px;
height: 50px;
color: #fff;
margin: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="child">one
<div class="child">one one</div>
</div>
<div class="child">two
<div class="child">two one</div>
</div>
<div class="child">three</div>
<div class="child">four
<div class="child">four one</div>
</div>
</div>
Run code
source
share