I have a div with an ID of '#Main" and I am trying to change CSS classes for this div with a collection of variables. using + ' ' + between the variables seems to add lots of empty space between classes therefore I was trying to use add all variables in an Array and use split property but so far I am unable to do so.
My code:
jQuery
var MainClasses ="";
var BackgroundColor="";
var BackgroundPattern ="";
var TxtColor="";
// Some code & conditions here which is assigning CSS classes to these variables
BackgroundColor = "Background-Red";
BackgroundPattern ="Pattern-2";
TxtColor = "Txt-Color-Green";
upDateTheme();
function upDateTheme() {
$('#Main').removeClass();
var ClassColletion = 'BackgroundColor, BackgroundPattern, TxtColor';
MainClasses = ClassColletion.split(' ');
$( '#Main' ).addClass(MainClasses );
}
Expected HTML Result
<div id="Main" class="Background-Red Pattern-2 Txt-Color-Green"> Some Content here </div>
2 Answers 2
A couple things here:
- You don't need to initialize your
MainClassesobject to a string. In fact, don't even use that extra variable. Just use yourClassCollection. - When you do the
split, split on the comma, not the space. - Put your variables inside an array.
- Use a loop to apply the class names (
addClass). Array objects are not supported out of the box.
This should get you going:
var BackgroundColor="";
var BackgroundPattern ="";
var TxtColor="";
// Some code & conditions here which is assigning CSS classes to these variables
BackgroundColor = "Background-Red";
BackgroundPattern ="Pattern-2";
TxtColor = "Txt-Color-Green";
upDateTheme();
function upDateTheme() {
$('#Main').removeClass();
var ClassColletion = [BackgroundColor,BackgroundPattern,TxtColor];
for (var i in ClassColletion) {
if (i && ClassColletion[i]) {
$( '#Main' ).addClass(ClassColletion[i]);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='Main'>main div</div>
5 Comments
BackgroundPattern has no class so there should not be extra space in HTML.the body of for in should be wrapped in an if statement to filter unwanted properties from the prototype. Any suggestions about this please?From jQuery documentation :
.addClass(className)className; Type: String; One or more space-separated classes to be added to the class attribute of each matched element.
Thererfore
BackgroundColor = "Background-Red";
BackgroundPattern = "Pattern-2";
TxtColor = "Txt-Color-Green";
upDateTheme();
function upDateTheme() {
$('#Main').removeClass();
var ClassColletion = [BackgroundColor, BackgroundPattern, TxtColor];
var MainClasses = ClassColletion.join(' ');
$('#Main').addClass(MainClasses);
}
Or, in a single expression :
function upDateTheme() {
$('#Main').removeClass().addClass([BackgroundColor, BackgroundPattern, TxtColor].join(' '));
}
var ClassColletion = [BackgroundColor, BackgroundPattern, TxtColor];