Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

classList.add() Insert variable instead of string

Tags:

javascript

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.

like image 285
Wiktor Kisielewski Avatar asked Nov 18 '25 06:11

Wiktor Kisielewski


1 Answers

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);
}
like image 142
Sami Hult Avatar answered Nov 19 '25 19:11

Sami Hult



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!