W3schools modal not working

I followed the w3schools tutorial for creating a modal. However when i click on the button, nothing happens. The only change i made to the tutorial was i used getElementbyClassName instead of id.
This is the tutorial link: https://www.w3schools.com/howto/howto_css_modals.asp

this is my modal code:

<button class="modal-btn"> Click me</button>

         <div class="modal-container">
 
            <div class="modal-content">

                <span class="close">&times;</span>

                <p> Some text in modal</p>

            </div>

        </div>


and this is my js file (I added everything in case one might be interfering)


$(window).on('scroll',function(){

  if ($(window).scrollTop()){

    $('nav').addClass('black');

  }

  else{

    $('nav').removeClass('black');

  }

})

$(document).ready(function(){

  $(".menu h4").click(function(){

    $("nav ul").toggleClass("active")

  })

})
> 
  //modal 

var modal = document.getElementsByClassName('modal-container');

 // Get the button that opens the modal

var btn = document.getElementsByClassName("modal-btn");

 // Get the <span> element that closes the modal

var span = document.getElementsByClassName("close");



// When the user clicks the button, open the modal 

 btn.onclick = function() {

modal[0].style.display = "block";

}



// When the user clicks on <span> (x), close the modal

span.onclick = function() {
 
modal.style.display = "none";

}

// When the user clicks anywhere outside of the modal, close it

window.onclick = function(event) {

if (event.target == modal) {

    modal.style.display = "none";
 }

}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Insted of using document.getElementsByClassName use document.getElementById…
because here W3Schools Tryit Editor

if you edit as a getElementsByClassName and run It will not work.

I asked the question on stackoverflow and I found out that the problem seems to be something with my pc. When I run the code on codepen, it works perfectly fine but on VS Code, nothing works. I’ve followed two other modal tutorials and they all don’t work. Do you have any suggestions.