简体   繁体   中英

'Cannot read property of appendChild' when trying to add and element to a list

I am trying to write a small script that takes in two value. One is a name and the other is a password. Here is the code:

 <textarea id="addName">Add a name</textarea> <textarea id="addPass">Add a hashed password</textarea> <button id="submit"> Submit user </button> <ul> <li>Name: Nicolas <br>Password (hashed): aslkdjf1231lk1jlkj5l4k5j64 </li> </ul> <script> document.getElementById("submit").onclick = function addUser() { var NAME = document.getElementById("addName"); var PASS = document.getElementById("addPass"); var unOrd = document.getElementById("ul"); var newLi = document.createElement("li"); unOrd.appendChild("newLi"); var newText = document.createTextNode("Name: " + NAME.value + " Password (hashed): " + PASS.value); newLi.appendChild("newText"); }; </script> 

I thought that, by putting the JS at the end of the HTML, it would be executed after the page is loaded and that it would solve the problem, but it is still returning: "Cannot read property 'appendChild' of null".

ul is not id but tag name of your list element. You can get it like this:

var unOrd = document.getElementsByTagName("ul")[0];

You're adding a string for appendChild instead of actual element and you don't have element with id ul try:

<textarea id="addName">Add a name</textarea>
<textarea id="addPass">Add a hashed password</textarea>
<button id="submit">
  Submit user
</button>
<ul id="someId">
  <li>Name: Nicolas
    <br>Password (hashed): aslkdjf1231lk1jlkj5l4k5j64
  </li>
</ul>
<script>
  document.getElementById("submit").onclick = function addUser() {
    var NAME = document.getElementById("addName");
    var PASS = document.getElementById("addPass");

    var unOrd = document.getElementById("someId");
    var newLi = document.createElement("li");
    unOrd.appendChild(newLi);

    var newText = document.createTextNode("Name: " + NAME.value + " Password (hashed): " + PASS.value);
    newLi.appendChild(newText);
  };
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM