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

Changing class using classlist.add not working

I wanted to change the name of the class ‘popup’ to ‘popup active’ when I click some button. The code isn’t working please help me out.

html:

<!DOCTYPE html>
<html>
<body>
    <script src="js.js"></script>
    <button class="button">click me</button>
    <div class="popup"></div>
</body>
</html>

js.js:

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

const but = document.querySelector('.button');
const pop = document.querySelector('.popup');

but.onclick = () => {
    pop.classList.add('active');
}

>Solution :

  1. Your script is executed before your DOM is built, place it after your elements:
<!DOCTYPE html>
<html>
<body>
    <button class="button">click me</button>
    <div class="popup"></div>
    <script src="js.js"></script>
</body>
</html>
  1. Or defer it:
<!DOCTYPE html>
<html>
<body>
    <script defer src="js.js"></script>
    <button class="button">click me</button>
    <div class="popup"></div>
</body>
</html>
  1. You could also watch for your DOM being loaded without changing your HTML:

window.addEventListener('DOMContentLoaded', () => {
const but = document.querySelector('.button');
const pop = document.querySelector('.popup');

but.onclick = () => {
    pop.classList.add('active');
}

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