DEV Community

Discussion on: How to show the clicked element only and hide others in Vanilla JavaScript?

Collapse
 
doublepicebs profile image
Doublepicebs • Edited

Good thing that you used loops! Usually, when the list of buttons is small, I define a function that resets everything, and set active styles on the pressed element.
Something like:

function activate(id)
    // All elements get the inactive here [...]
    document.querySelector(id).classList.add("active");
Enter fullscreen mode Exit fullscreen mode

A good hack for me is to put three text elements and hide all of them using css, and when a button gets pressed it will show it's own associated text element.
Your way is still way better than mine.

Collapse
 
mohdhussein profile image
Mohammed

Loops saved me here. My first solution was using โ€˜if elseโ€™ statement for each one. So the bigger the list the more I write.

I did what you said at first but I added more since its common for the first button to be clicked by default.

Thank you for your reply. ๐Ÿ‘