Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
select second element of a specified class using jQuery

I have two elements with class of monkey on the page, and I want to attach one of them to a on click event listener. they maybe siblings or completely independent elements. Now I want to select the second element (which comes after the first one in html code)...

This will select both of them and the event listener fires twice:

const monkey = $(".monkey");

I used a lot of things with no luck to select the second element:

$(".monkey").get(1); 
$(".monkey")[1] 

Edit:

Here is the relation of two monkey elements one at the top and at the bottom of the image:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use jQuery.eq as a function or as a selector.

You can make use of a ternary operator to check whether the number of selected monkey elements is greater than 1, and if so, set monkey to the second element. Otherwise, don't modify monkey.

var monkey = $(".monkey"); //same as $(".monkey:eq(1)")
monkey = monkey.length > 1 ? monkey.eq(1) : monkey;
monkey.on('click', function(){
  console.log('click');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="monkey">first element</div>
<div class="monkey">second element</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda