Aliana
Aliana

Reputation: 53

How to add css to dynamic div Id

I want to apply css to dynamic div id.

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    c.style.backgroundColor = 'rgb(255, 125, 115)';
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
}  

here "item_" + i is a dynamic Ids of every rows.like item_1,item_2,item_3 etc. So I want to add css in some of the rows. ie . item_1 and item_3 or else.

So how can this possible.

Upvotes: 0

Views: 2203

Answers (4)

Rajat Bhadauria
Rajat Bhadauria

Reputation: 260

In order to add CSS to dynamic div you can use the following syntax

$("div"+dynamic_id).css({"color":"rgb(255, 125, 115)"});

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

You are trying to apply the style property to string instead you need to get the element by id. Use documet.getElementById() for that

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    document.getElementById(c).style.backgroundColor = 'rgb(255, 125, 115)';
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
} 

Or use jQuery id-selector and for applying css use css()

var status = var status = item.down().next().innerHtml();
if(status == "test")
{  
    var c = 'item_'+i ;
    $('#'+c).css('background-color','rgb(255, 125, 115)');
    //'item'+ i.style.backgroundColor = 'rgb(255, 125, 115)';
} 

Upvotes: 1

Yakng
Yakng

Reputation: 135

There are many ways for achieving result you want.In addition to others answers you can also do like this with jquery

$("div#"+dynamic_id).css("background-color", "rgb(255, 125, 115)");

Upvotes: 0

Techie
Techie

Reputation: 1491

You can use as mentioned other users, or you can also use the below, basically if you use pure JavaScript then you have to identify the element first by using the function document.getElementbyId

var c = document.getElementbyId('item_' + i);
c.style.backgroundColor = 'rgb(255, 125, 115)';

Upvotes: 0

Related Questions