Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting only first level element, not child elements with the same element name

Tags:

jquery

css

How would I select only the first level .block and not any of the children?

$('.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>
like image 347
tester Avatar asked Apr 09 '10 00:04

tester


People also ask

How do you select all child elements except first?

By using the :not(:first-child) selector, you remove that problem. You can use this selector on every HTML element. Another common use case is if you use an unordered list <ul> for your menu.

How do you select an element with the same class name?

How can I get all of the elements with the same class name in JavaScript? Using JavaScript – querySelector() function The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.

How can I select all children of an element except the last child?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

What is the class used to select an element which has no child?

The :empty CSS pseudo-class represents any element that has no children.


2 Answers

If that sample 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' });
like image 156
alex Avatar answered Sep 21 '22 10:09

alex


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

$('.block:first')

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

Note that :first is not the same as :first-child.

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

$('.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, then remove any matched elements that have an ancestor matching .block. (You can replace closest with parent if you want to).

like image 36
SLaks Avatar answered Sep 22 '22 10:09

SLaks