PeterP
PeterP

Reputation: 71

Setting javascript variable to use in div id

So I have this example here where I have javascript variable "id" which I want to put into a divs id.

<div id="(var id here)" style="width:100px; height:100px; border:5px solid black; ">

</div>

<script>
var id;

var color = blue

$('#(var id here)').css({"background-color" : color});
</script>

This is just an example and it's important that the div id is the variable id, not just a name. Hope someone can help me. Ask me if you don't understand! Thanks

Upvotes: 0

Views: 3129

Answers (3)

GG.
GG.

Reputation: 21854

var id = 1;

$('div').attr('id', id).css('background-color', 'blue');

The selector isn't really good but I don't know how you create your <div>.

Upvotes: 0

Romain
Romain

Reputation: 1948

I think you are doing it the wrong way.

What you need to do is create different css class with different attribute.

.blue{ background-color : blue; }
.green{ background-color : green; }

And then, with your js code, you load the selected class to the element.

Note: this isn't a good answer to your question but a different way to do it.

Hope this help

Upvotes: 0

Danny
Danny

Reputation: 7518

$('#' + id).css({"background-color" : color});

Upvotes: 3

Related Questions