I want to write a vanilla js function that have the same function as in jQuery addClass() function. I have wrote these code below.
function checkType(value){ //get type of target
var name = "";
var type = value.split("");
for(var i=1; i<type.length; i++){
name = name + type[i];
}
if(type[0] == "#"){ //if id
return document.getElementById(name); //return id
}else if(type[0] == "."){ //if class
return document.getElementsByClassName(name); //return class
}else{
return null;
}
}
function classesToArray(value){
if(value != null){
value = value.split(" ");
return value;
}
return [];
}
function addClass(target, value) {
var element = checkType(target);
var classes = classesToArray(value);
if(element != null){
classes.forEach(function(classItem){
if(element.length){
for(var i = 0; i < element.length; i++){
element[i].className += " " + classItem;
}
}else{
element.className += " " + classItem;
}
});
}
}
So the way to use it is as below
addClass('.elementIdName','nameOfClassToAdd'); //target Id if begin with .
addClass('#elementClassName','nameOfClassToAdd'); //target className if begin with #
addClass('.elementIdName', 'nameOfClass1 nameOfClass2'); //you can also add multiple class names
The code works. But I know there’s a lot of room to improve it. I’d really appreciate if someone can show me the ropes on what should i look for to improve this. Thanks