Home > OS >  Getting all classes from one element and adding them to another element in vanilla JavaScript
Getting all classes from one element and adding them to another element in vanilla JavaScript

Time:02-26

I'm trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?

    let classes = this.nextElementSibling.classList;      // get classes from target element
    classes  = '';                                        // convert classlist object to string
    let class_array = classes.split(' ');                 // convert string to array
    const my_div = document.createElement('div');         // create a new div
    for(i=0; i<class_array.length; i  ) {                 // loop through array and add classes to the div
      my_div.classList.add(class_array[i]);
    }

Thanks in advance.

CodePudding user response:

The className will give you a space-separated string of class names an element has. Just use that.

const my_div = document.createElement('div');
my_div.className = this.nextElementSibling.className;
  • Related