Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!