Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading