Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find only not nested elements

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/

like image 519
Marc Avatar asked Nov 02 '22 13:11

Marc


1 Answers

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

like image 140
bhb Avatar answered Nov 09 '22 13:11

bhb