goldpotatos
goldpotatos

Reputation: 27

'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".

Upvotes: 0

Views: 92

Answers (2)

jcubic
jcubic

Reputation: 66540

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>

Upvotes: 0

madox2
madox2

Reputation: 51861

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

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

Upvotes: 1

Related Questions