What is ":eq(0)" for and how?

Asked

Viewed 1,084 times

3

I was watching a tutorial on slider for jQuery, and in a part of the code, in which the goal was to return to the first image, the author of the code did it in a way that I do not know, and also did not know how to search it in 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 it work :eq(0) ?

1 answer

5


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

That is, if you have n images descended from #slide then eq(0) will choose the first only. 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>
<div id="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 as well:

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

    Look Sergio, spectacular reply, responded perfectly, and even suggested other ways, congratulations for the work you’ve been doing here, see more!

  • @Alexandrec.Caus thank you!

  • Just reinforcing the beautiful explanation of @Sergio, when we use $('#slide img').eq(-1), return the last element of the group. Similarly, we can use the "pseudo-selector" :last.

Browser other questions tagged

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