1

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, in one line (without the use of assigning variables) how would I force JavaScript to return an element that has a text value instead of only returning the text value?
@JeremyJeminMunshi: See Rajkumar's answer stackoverflow.com/a/52982394/4012073
1

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++));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.