Wiktor Kisielewski
Wiktor Kisielewski

Reputation: 437

classList.add() Insert variable instead of string

I'm trying to make a loop that changes the class of an element everytime it is executed. The problem is that

classList.add('something')

requires string and I need to put a variable there, here is my code:

const head = document.createElement('div');

function change_head() {
    var head_class = [
        {name: "bold"},
        {name: "rainbow_head"},
        {name: "hut_head"},
        {name: "beats_head"}
    ];
    for (let i = 0; i < head_class.length; i += 1){
        diffrent_head = head_class[i];
        head.classList.add(head_class[i]);
    }
};

Hope it is possible to somehow use a variable here.

Upvotes: 3

Views: 2498

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371138

The problem is that you need to access the .name property in order to get to the string:

head.classList.add(head_class[i].name);

const head = document.createElement('div');

function change_head() {
    var head_class = [
        {name: "bold"},
        {name: "rainbow_head"},
        {name: "hut_head"},
        {name: "beats_head"}
    ];
    for (let i = 0; i < head_class.length; i += 1){
        diffrent_head = head_class[i];
        head.classList.add(head_class[i].name);
    }
}
change_head();
console.log(head.className);

But there's a better looking option - you can .map the head_class to just the strings (extract the .name property from each), then spread the array of strings into .add, resulting in .add being called only once:

const head = document.createElement('div');

function change_head() {
    var head_class = [
        {name: "bold"},
        {name: "rainbow_head"},
        {name: "hut_head"},
        {name: "beats_head"}
    ];
    head.classList.add(
      ...head_class.map(({ name }) => name)
    );
}
change_head();
console.log(head.className);

Upvotes: 0

Sami Hult
Sami Hult

Reputation: 3082

In your head_class array, you have objects with a field name, which has a string value. Use that:

for (let i = 0; i < head_class.length; i += 1){
    head.classList.add(head_class[i].name);
}

Upvotes: 1

Related Questions