Search code examples
javascriptjqueryaddclassremoveclass

Using multiple variables in addClass/removeClass


I can use one variable in addClass/removeClass

html:

<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
</body>

css:

p {
margin: 8px;
font-size: 16px;
}
.selected {
color: red;
}
.highlights {
background: yellow;
}

js:

var css1="selected";
var css2="highlights";

$( "p:last" ).addClass(css1);

I want use css1 and css2 variables in addClass method. I tried these:

$( "p:last" ).addClass(css1 css2);
$( "p:last" ).addClass("css1 css2");

They don't work.

If I use this:

var css3="selected highlights"
$( "p:last" ).addClass(css3);

it works

But how can I use css1 and css2 variables in addClass method ?

You can try on http://jsfiddle.net/hasyo1qm/

Thanks.


Solution

  • This works:

    $( "p:last" ).addClass(css1+" "+ css2);
    

    Both class names need a space between them, so using concatenation we have to add a space between them, otherwise it will not behave right.

    UPDATED FIDDLE:

    http://jsfiddle.net/ehsansajjad465/hasyo1qm/2/