'How to remove class on link click using pure js?

How to remove the 'open' class when clicking on

<a class="menu-link"></a>

enter image description here

// this is how I add the class on button click
document.getElementById('navigation-toggle').onclick = function() {
   document.getElementById('site-navigation').classList.toggle('open');
}
// and i'm trying to remove it on click on the link
document.querySelector('.menu-link').onclick = function() {
   document.getElementById('site-navigation').classList.remove('open');
}


Solution 1:[1]

You have multiple links so you have to add event listener to all of them

document.querySelectorAll('.menu-link').forEach(link => link.onclick = function() {
   document.getElementById('site-navigation').classList.remove('open');
})

I would also consider using addEventListener. And you can read about event delegation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konrad Linkowski