0

I have the following code

var replyName = "1";

var test = "<div id=replyName></div>"

I want to set the class name to the variable replyName, what should I do?

2 Answers 2

3

You really have three options.

  1. Use the opposite quote style, in this case single quotes, to surround the attribute declaration.

    var test = "<div id='"+replyName+"' class='"+replyName+"'></div>";
    
  2. Use escaped quotes.

    var test = "<div id=\""+replyName+"\" class=\""+replyName+"\"></div>";
    
  3. Use no quotes (beware this can cause problems if you have spaces, for instance, although an ID should not have spaces anyways). However, multiple classes would have spaces, so be careful, since in the below case those spaces would be interpreted as different attributes.

    var test = "<div id="+replyName+" class="+replyName+"></div>"
    

I would use 1 or 2, although 3 is valid under the right conditions.

Also, as Mikola mentions in a comment below, if you flip the string quote style to single quotes, you'll have to use the opposite quoted style for your attribute a la 1, and escape single quotes like I do double quotes in 2.

http://jsfiddle.net/XyVuN/1/

Sign up to request clarification or add additional context in comments.

2 Comments

Another way is to use: var test = '<div id="' + replyName + '"></div>';
@Mikola - Yes, that's true; it's just the opposite of what the OP had included in the question.
1
var replyName = "1";
var test = "<div id='" + replyName + "'></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.