Given this HTML structure
<div class="item">
<div class="item">
select me
<div class="item">don't select me</div>
</div>
<span>
<div class="item">select me</div>
</span>
</div>
And this jQuery:
var firstItem = $('.item:first');
var selector = firstItem.find('.item');
selector.css('color', 'red');
I am looking for a way to mark only the not nested .item elements inside the firstItem div. The tricky part here is that the firstItem itself is (or can be) already nested in .item class.
What have I tried?
firstItem.find('.item').not('.item .item')
This does not work because the first level we are starting in is already an .item class. And that can be nested x times already so it could be .item .item .item .item or whatever. And the starting element does not have an ID so I cannot use that in the selector as well.
I think the solution should be something like a reversed .closest() which travels down the DOM and does not search the contents of an already found item.
Prepared a jsFiddle here: http://jsfiddle.net/LWmy3/2/
Try this
var firstItem = $('.item:first');
$(firstItem).find(".item").each(function () {
//console.log($(this).parent(".item")[0])
if ($(this).parent(".item")[0] === undefined) {
$(this).css('color', 'red')
} else if ($(this).parent(".item")[0] != $(firstItem)[0]) {
$(this).css('color', 'cyan')
} else {
$(this).css('color', 'red')
}
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With