Sara Ree
Sara Ree

Reputation: 3543

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

Upvotes: 1

Views: 150

Answers (1)

Spectric
Spectric

Reputation: 31987

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>

Upvotes: 1

Related Questions