Select only the first level item, not child items with the same item name

How to choose only the first level .block, and not any of them?

$('.block:not("Children of this here")') <-

 <div class="block"> <!-- this --> <div class="block"> <!-- not this --> <div class="block"> <!-- not this --> </div> </div> </div> <div class="block"> <!-- and this --> <div class="block"> <!-- not this --> <div class="block"> <!-- not this --> </div> </div> </div> 
+6
jquery css
source share
4 answers

If this layout markup has a parent element, for example, below. If not, the parent will be body if it is valid HTML.

HTML

 <div id="parent"> <div class="block"> <div class="block"> <div class="block"> </div> </div> </div> </div> 

JQuery

 $('#parent > .block').css({ border: '1px solid red' }); 
+8
source share

You can use the :first selector to select only the first matching .block element:

 $('.block:first') 

This works because jQuery matches elements in the order of the document. The outermost .block element will be the first element matched by .block , and :first will only filter to return it.

Note that :first does not match :first-child .

EDIT . In response to your update, you can write the following, which will only work if all the elements are nested in three depths:

 $('.block:note(:has(.block .block))') 

You can write a more robust solution using a function call:

 $('.block').not(function() { return $(this).closest('.block').length; }) 

This will find all .block elements, and then remove any matched elements that have a match with the .block ancestor. (You can replace closest with parent if you want).

+2
source share
 $('#parent').children('.block'); 

Take a look . children () jQuery reference.

+1
source share

Try the following:

 $("div.block:first").<what you want to do> 

edit: spaces removed. thanks :-) .... now that should be fine.

NTN

0
source share

All Articles