Home > Net >  Why is a new li not added at the end?
Why is a new li not added at the end?

Time:12-02

I'm new to javascript and just completed a tutorial on DOM manipulation.

However, new lis are added after the fist li, not at the end (unlike the tutorial).

I would love to understand why they are added exactly there and how to add them at the end.

const userList = document.querySelector(".name-list li");
const listInput = document.querySelector(".list-input");
const addListBtn = document.querySelector(".addListBtn");

addListBtn.addEventListener("click", function(){
    const newLi = document.createElement("li");
    const liContent = document.createTextNode(listInput.value);
    newLi.appendChild(liContent);
    userList.appendChild(newLi);
});
<button class="addListBtn">Click me!</button>
<ul class="name-list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<input type="text" class="list-input">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You're appending to userList which is defined like:

const userList = document.querySelector(".name-list li");

Note the li in the selector, so you're adding to a li


Update it to:

const userList = document.querySelector(".name-list");

So it's the list itself, not the li inside.

const userList = document.querySelector(".name-list");
const listInput = document.querySelector(".list-input");
const addListBtn = document.querySelector(".addListBtn");

addListBtn.addEventListener("click", function(){
    const newLi = document.createElement("li");
    const liContent = document.createTextNode(listInput.value);
    newLi.appendChild(liContent);
    userList.appendChild(newLi);
});
<button class="addListBtn">Click me!</button>
<ul class="name-list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<input type="text" class="list-input">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Remove li const userList = document.querySelector(".name-list");

const userList = document.querySelector(".name-list");
const listInput = document.querySelector(".list-input");
const addListBtn = document.querySelector(".addListBtn");

addListBtn.addEventListener("click", function(){
    const newLi = document.createElement("li");
    const liContent = document.createTextNode(listInput.value);
    newLi.appendChild(liContent);
    userList.appendChild(newLi);
});
<button class="addListBtn">Click me!</button>
<ul class="name-list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<input type="text" class="list-input">
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

For example:

function function1() {
  var ul = document. getElementById("list");
  var li = document. createElement("li");
  li. appendChild(document. createTextNode("Four"));
  ul. appendChild(li);
}
  • Related