How can I get the first element of each parent element?

Asked

Viewed 3,908 times

8

I have a structure like this:

<div class="container">
    <span class="iconset"></span> <!-- primeiro elemento -->
    <span class="iconset"></span>
</div>
<div class="container">
    <span class="iconset"></span> <!-- primeiro elemento -->
    <span class="iconset"></span>
</div>

I need to select the first elements of each block. If I try to get this way:

$(".container .iconset:first");

I get only 1 element, but in this example I want to get the 2 elements.

How can I do that?

2 answers

13


There are several ways to do this with jQuery.

To select both spans from the example:

  1. Using the pseudo-class :first-child on the selector:

    var primeiros = $(".container .iconset:first-child");
    
  2. Using the pseudo-class :nth-child on the selector:

    var primeiros = $(".container .iconset:nth-child(1)");
    
  3. Using the pseudo-class :first-of-type (selecting the first element of a certain type, in this case, spans):

    var primeiros = $(".container .iconset:first-of-type");
    

To select only the first span of the first container:

  1. With the method first:

    var primeiro = $(".container .iconset").first();
    
  2. Using the pseudo-class :first (jQuery extension, not part of CSS):

    var primeiro = $(".container .iconset:first");
    
  3. With the method eq:

    var primeiro = $(".container .iconset").eq(0);
    
  4. With the pseudo-class :eq (jQuery extension, not part of CSS):

    var primeiro = $(".container .iconset:eq(0)");
    

The difference is that all methods of this second group first select all elements that meet the selector, and only then take the first element between them.

1

There is the selector :nth-child().

You can use by passing the parameter 1 to get these elements. I see a example in jsFiddle.

var elementos = $(".container .iconset:nth-child(1)");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.