user4774980
user4774980

Reputation:

jQuery equivalent for getElementsByClassName('name')[n]?

Is there any jQuery equivalent similar to

$(document).ready(function(){
    $('para')[2].css("color","red");
});

for the code below

document.getElementsByClassName('para')[2].style.color = "red";
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
I want the CSS to be applied to the nth paragraph.

Upvotes: 1

Views: 3162

Answers (4)

scronide
scronide

Reputation: 12248

I would normally use the :eq() selector for this:

$('.para:eq(2)').css('color', 'red');

Upvotes: 0

meteor
meteor

Reputation: 2568

You can use n-th child to set the style accordingly

$(document).ready(function(){
$( ".para:nth-child(2)" ).css("color","red");
});

Upvotes: 1

scniro
scniro

Reputation: 16989

A jQuery alternative could be crafted as follows. Note that nth-of-type is not zero index based

$('p.para:nth-of-type(3)').css('color', 'red')

JSFiddle Link

Upvotes: 1

Adam Kewley
Adam Kewley

Reputation: 1234

Try .eq if you want to access a specific jQuery element from a list of matched stuff:

$(".para").eq(2).css("color","red");

Edit: The dot notation, .para, is functionally equivalent to getElementsByClassName("para")

Upvotes: 3

Related Questions