BuzzFuzz
BuzzFuzz

Reputation: 165

Almost same code, different output. What is JavaScript doing differently here?

First Code!

x = 6;

document.getElementById("btn").addEventListener("click", function() {
  var list = document.createElement("li");
  var apple = document.getElementById("our-list");

  list.appendChild(document.createTextNode("Something " + x++));
  apple.appendChild(list);
});
<body>
  <button id="btn">Click</button>

  <ul id="our-list">
    <li>Something 1</li>
    <li>Something 2</li>
    <li>Something 3</li>
    <li>Something 4</li>
    <li>Something 5</li>
  </ul>

  <script src="./javascript.js"></script>
</body>

Test Code! (Yes, I know it looks disgusting but its only for understanding and testing purpose.)

var x = 6;

document.getElementById("btn").addEventListener("click", function() {
  document.getElementById("our-list").appendChild(document.createElement("li").appendChild(document.createTextNode("Something " + x++)));
});
<body>
  <button id="btn">Click</button>

  <ul id="our-list">
    <li>Something 1</li>
    <li>Something 2</li>
    <li>Something 3</li>
    <li>Something 4</li>
    <li>Something 5</li>
  </ul>

  <script src="./javascript.js"></script>
</body>

Why is this not creating a list element? It seems like its entirely skipping the document.createElement("li") and appending a TextNode straight away!

Upvotes: 1

Views: 55

Answers (2)

Rajkumar A
Rajkumar A

Reputation: 87

You can use the below code to do the same in one line without using variables. Hope this will help you.

document.getElementById("our-list").appendChild(document.createElement("li")).appendChild(document.createTextNode("Something " + x++));

Upvotes: 1

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

Because, in your second code, you are appending the return value of

document.createElement("li").appendChild(document.createTextNode("Something " + x++))

to the document.getElementById("our-list").

If you look at the documentation of appendChild, this method returns the appended child node. Therefore, when you do

document.createElement("li")
.appendChild(document.createTextNode("Something " + x++))

what you are appending to the our-list is not the newly created li element, but the child note which you intended to be inside that li node.

Upvotes: 2

Related Questions