Westly
Westly

Reputation: 43

Select only one single class in jquery

Says I have multiple of class named item.

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

But I only want to show one, sequence doesn't' matter. How do I do that?

$('.item').show() // this will show all of them

Upvotes: 2

Views: 59

Answers (2)

saikumar
saikumar

Reputation: 1051

$('.item').eq(0).show() // it will display first item

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337714

You can use any of the following methods to choose a particular element from the matched set:

// show the first .item only  
$('.item:first').show();
$('.item').first().show();

// show the last .item only
$('.item:last').show();
$('.item').last().show();

// show the second .item only
$('.item:eq(1)').show();
$('.item').eq(1).show();

Note that eq takes a parameter which is the index of the element you want to target.

Upvotes: 4

Related Questions