How do I select only one element with a class that exists in other elements?

3

I'm in a situation where I have three elements on one page.

<img class="imagem" />
<img class="imagem" />
<img class="imagem" />

I would like to select the second element of these 3 classes. How can I do this via jquery?

    
asked by anonymous 14.03.2016 / 15:43

2 answers

3

Use the jQuery eq (indice) selector to select an element by its index.

var $elemento = $('.imagem:eq(1)');

See the example below by manipulating the element.

var $elemento = $('.imagem:eq(1)');
$elemento.attr('style', 'border:1px solid red');
.imagem {
  width: 30px;
  height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><imgclass="imagem" />
<img class="imagem" />
<img class="imagem" />
    
14.03.2016 / 15:52
4

Selecting by element index, you have the following options:

$('.imagem')[index];
$('.imagem').get(index);
$('.imagem:eq('+index+')');

Note: Remembering that the index starts from zero.

    
14.03.2016 / 15:51