Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda