0

I have tried to add, remove and toggle classstyles to 3 <li> s when user click on 3 buttons having ids 'add' 'delete' and 'toggle' respectively. But the codes repeat itself other than the classList method name and button id.

is there anyway i could write a function to avoid repetition?

here is my code.

document.querySelector('#add').addEventListener('click',()=>{
    document.querySelectorAll('#todos li').forEach((li)=>{
        li.classList.add('listStyles');
    })
});
document.querySelector('#delete').addEventListener('click',()=>{
    document.querySelectorAll('#todos li').forEach((li)=>{
        li.classList.remove('listStyles');
    })
});
document.querySelector('#toggle').addEventListener('click',()=>{
    document.querySelectorAll('#todos li').forEach((li)=>{
        li.classList.toggle('listStyles');
    })
});

1 Answer 1

1

You could do it like this:

function modifyClass(action) {
    document.querySelectorAll('#todos li').forEach((li)=>{
        li.classList[action]('listStyles');
    })
}

document.querySelector('#add').addEventListener('click', ()=>{ modifyClass("add") });
document.querySelector('#delete').addEventListener('click', ()=>{ modifyClass("remove") });
document.querySelector('#toggle').addEventListener('click', ()=>{ modifyClass("toggle") });

If you changed the element #delete to #remove, you could do:

for (const action of ["add", "remove", "toggle"])
    document.getElementById(action).addEventListener("click", ()=>{
        document.querySelectorAll('#todos li').forEach((li)=>{
            li.classList[action]('listStyles');
        });
    });
Sign up to request clarification or add additional context in comments.

6 Comments

You can use array to remove more redundancy. +1
Great idea, but #delete needs to be changed to #remove.
i have tried the for of loop method. but the last action (in this case 'toggle') got applied to every button
You are right. I forgot to put let or const before action, so action ended up in the global scope. I edited my question.
ohh i see. i added a function inside loop and and it works now
|

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.