Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
How to improve my add class to element functions

I want to write a vanilla js function that works like jQuery's addClass() function. I have written the 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 could show me the ropes on what should I look for to improve this. Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is no need to write your own addClass function.

You can use this:

let el = document.querySelector("#your_element_id");
if(el) {
   el.classList.add("your class name");
}

source: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!