user1785251
user1785251

Reputation:

How to give background color dynamically using jQuery index?

I have a markup like this:

<div class="container">
    <div>one</div>
    <div>two</div>
    <div>three</div>
    <div>four</div>
    <div>five</div>
</div>

I want to give background color using jQuery index() for any div inside the container (I will get indexes dynamically from the server).

Upvotes: 1

Views: 163

Answers (3)

Jai
Jai

Reputation: 74738

Try with .eq() and :eq():

$('.container div').eq(idx).css('background','purple');

$('.container div:eq('+idx+')').css('background','purple');

Upvotes: 2

bipen
bipen

Reputation: 36541

use children and eq()

 $(".container").children().eq(0).css("background-color",'red') //this will change background of first div

with your requirement

 var yourindex='0';
 $(".container").children().eq(yourindex).css("background-color",'red')

fiddle here

Upvotes: 3

Sharad
Sharad

Reputation: 743

$(".container div:nth-child(0)").css("someecssName)

Upvotes: 0

Related Questions