Q:

Local copy of JavaScript code not working when it's online demo is

I'm learning JavaScript using MDN web docs. In that, the following piece of code is given -

function CreateParagraph() {
  var para = document.createElement('p');
  para.textContent = 'You clicked the button!';
  document.body.appendChild(para);

  var buttons = document.querySelectorAll('button');

  for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', createParagraph);
  }
}
<button>Click me</button>

The online demo of this code works but when I made a local copy, that is not working. What exactly is wrong here?

A:

Have fun on your Javascript journey. MDN is a good place to start.
If you look at the example code again. Pay close attention to opening and closing braces {}. In your local example you've put all the code inside your function.
This is the example from MDN. See how it differs from yours?

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>Apply JavaScript example</title>
  </head>
  <body>
    <button>Click me</button>

    <script>
      function createParagraph() {
        var para = document.createElement('p');
        para.textContent = 'You clicked the button!';
        document.body.appendChild(para);
      }

      var buttons = document.querySelectorAll('button');

      for(var i = 0; i < buttons.length ; i++) {
        buttons[i].addEventListener('click', createParagraph);
      }
    </script>
  </body>
</html>

