What does "eq (0)" serve and how does it work?

3

I was seeing a slider tutorial for jQuery, and in a part of the code, in which the objective was to go back to the first image, the code author did in a way I do not know, I knew how to search this on Google:

$(".ativo").fadeOut().removeClass("ativo");
$("#slide img:eq(0)").fadeIn().addClass("ativo");

The part of, $("#slide img:eq(0)") left me confused, img:eq(0) ?

How does this work for :eq(0) ?

    
asked by anonymous 02.01.2015 / 16:04

1 answer

5

:eq() is a pseudo-selector for index .

That is, if you have n descendant images of #slide then eq(0) will choose the first only. It's worth remembering that index starts at zero.

Example:

$("#slide div:eq(0)").css('color', 'blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="slide">
    <div>numero 1</div> <!-- esta vai ficar azul -->
    <div>numero 2</div>
    <div>numero 3</div>
    <div>numero 4</div>
</div>

In this case it could be written like this:

$("#slide img").eq(0) // exemplo: http://jsfiddle.net/9hue60dd/1/
$("#slide img:first") // exemplo: http://jsfiddle.net/9hue60dd/
    
02.01.2015 / 16:07