3

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.

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.