skip to Main Content

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:

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

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

2

Answers


  1. Your script is executed before your DOM is built, place it after your elements or defer it.

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

    OR

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

    You could also watch for your DOM being loaded:

    
    window.addEventListener('DOMContentLoaded', () => {
    const but = document.querySelector('.button');
    const pop = document.querySelector('.popup');
    
    but.onclick = () => {
        pop.classList.add('active');
    }
    
    });
    
    Login or Signup to reply.
  2. there is a small conflict in the place of script Here is a corrected code

    const but = document.querySelector('.button');
    const pop = document.querySelector('.popup');
    
    but.onclick = () => {
        pop.classList.add('active');
    }
    <!DOCTYPE html>
    <html>
    <body>
        <button class="button">click me</button>
        <div class="popup"></div>
         <script src="js.js"></script>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search