0

I am a beginner in Javascript. I am doing some exercises and coming across the error listed above for the 'onclick'.

I have looked at other questions on this forum and it has not be helpful for me. I have looked over syntax numerous times in both my html and JS and can't find anything!

var item1;
var item2;
var item3;

document.getElementById("changeList").onclick = newList;

function newList() {
  item1 = prompt("Enter a new first thing:");
  item2 = prompt("Enter a new second thing:");
  item3 = prompt("Enter a new third thing:");
  updateList();
}

function updateList() {
  document.getElementById("firstThing").innerHTML = item1;
  document.getElementById("secondThing").innerHTML = item2;
  document.getElementById("thirdThing").innerHTML = item3;
}
<html>

<head>
  <meta charset="UTF-8">
  <title>Javascript Practice</title>
  <script src="main.js"></script>
</head>

<body>
  <h1 id="myName">Angie</h1>
  <hr>
  <p id="aboutMe"><em>I am trying to learn this damn javascript and stick with it.</em></p>
  <h2>Things I like</h2>
  <p>Here are some of the things I like to do:</p>
  <ul>
    <li id=firstThing>Dance</li>
    <li id=secondThing>Write</li>
    <li id=thirdThing>Travel</li>
  </ul>
  <button id="changeList" type="button">Change Your List</button>
</body>

</html>
Vivek
  • 1,465
  • 14
  • 29
angiec
  • 1
  • 1

2 Answers2

0

You can try placing your script tag at the bottom of the page as suggested by lealceldeiro or you can wait for the DOM to load fully before adding your event listener for onclick like so:

//Replace this line
document.getElementById("changeList").onclick = newList;

//With the following, this fires an event when the DOM has fully loaded
//This will ensure your element has been rendered into the DOM
document.addEventListener("DOMContentLoaded", function(event) { 
    document.getElementById("changeList").onclick = newList;
});
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
0

Try changing your html line to :

<button id="changeList" type="button" onclick = newList();>Change Your List</button>

and remove this line from your JS

document.getElementById("changeList").onclick = newList;
Mehravish Temkar
  • 4,275
  • 3
  • 25
  • 44
user2438439
  • 21
  • 1
  • 3
  • I don't know what happened to this post. It should have said: Try changing your html line to : and remove this line from your JS document.getElementById("changeList").onclick = newList; – user2438439 Jun 19 '18 at 19:45
  • This answer worked perfectly! So now what I need to look at is why this worked. It's strange. I have been working through this book on javascript and I did everything verbatim they asked when writing this code. So I am curious why it didn't work their way. Thank you again! – angiec Jun 20 '18 at 17:02