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

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 it 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 this?

    
asked by anonymous 24.12.2013 / 20:12

2 answers

13

There are several ways to do this with jQuery.

To select both of the example spans:

  • Using the pseudoclasse :first-child in the selector:

    var primeiros = $(".container .iconset:first-child");
    
  • Using pseudoclasse :nth-child in the selector:

    var primeiros = $(".container .iconset:nth-child(1)");
    
  • Using pseudoclasse :first-of-type (which selects 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:

  • With the first method:

    var primeiro = $(".container .iconset").first();
    
  • Using pseudoclasse :first (jQuery extension, not part of CSS):

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

    var primeiro = $(".container .iconset").eq(0);
    
  • With pseudoclasse :eq (jQuery extension, not part of CSS):

    var primeiro = $(".container .iconset:eq(0)");
    
  • The difference is that all the methods in this second group first select all the elements that meet the selector, and only then takes the first element between them.

        
    24.12.2013 / 20:44
    1

    There is the :nth-child() selector.

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

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