Joe Joe - 2 months ago 7
CSS Question

How to select all items in array at once, and add class to them

I would like this function to hide buttons in my html, by giving them css .hidden attribute. I have tried [0, 1, 2, 3, 4] but it does not work as supposed, this code works but I was wondering if there is a more efficient way to do it..?

function hideButtons(){
var buttons = document.querySelectorAll('.buttons');
buttons[0].classList.add('hidden');
buttons[1].classList.add('hidden');
buttons[2].classList.add('hidden');
buttons[3].classList.add('hidden');
buttons[4].classList.add('hidden');
}

Answer

Use a simple loop

for(var i = 0; i < buttons.length; i++){
    buttons[i].classList.add('hidden');
}
Comments