0

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

3
  • Are you saying you want to set the div's id to the variable id? Also, use var color = "blue"; otherwise you'll get an undefined variable error. Commented Oct 3, 2013 at 13:24
  • What do you want now ? Commented Oct 3, 2013 at 13:25
  • You are asking how to use a string? Commented Oct 3, 2013 at 13:25

3 Answers 3

3
$('#' + id).css({"background-color" : color});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.