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

Asked

Viewed 237 times

3

I’m in a situation where I have three elements on the same page.

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

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

2 answers

4

Selecting by the element index, you have the following options:

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

Note: Remembering that the index starts from scratch.

3


Use the selector switch eq(Index) jQuery to select an element by its content.

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

See the example below 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>
<img class="imagem" />
<img class="imagem" />
<img class="imagem" />

  • 2

    Remembering that sometimes depending on the need of the selection can use the id, which serves precisely to select specific elements and that there is no other equal in the DOM. The id is has more priority over the class in selections.

Browser other questions tagged

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