PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] How to append HTML element multiple times

 August 13, 2022     dom, html, javascript, object     No comments   

Issue

I've added an event to my app(clicking & enter), the main goal of it is to add an input value every time the user uses that event, everything works just fine in the first shot but after that, the code stops to work, so please could you give me any suggestions or possible solutions?

this is my js code :

// important vars 
const btn = document.getElementById('btn');
const inputV = document.getElementById('input').value;
const input = document.getElementById('input');
const todoUl = document.createElement("ul");
const todoLi = document.createElement("li")
const todoList = document.getElementById('todolist'); // this the div that contain ul and li
const form = document.getElementById('from');

// this function is for add input value and create list's 
function addTodo(todo) {
    form.appendChild(todoUl);
    todoUl.appendChild(todoLi);
    todoLi.innerText = inputV    
};

// later ..
form.addEventListener('submit' , (e) => {
    e.preventDefault(); 

    addTodo()

});

update : thank you all for your answers <3;


Solution

appendChild method appends a Node to the elements childlist, but also removes it from the original place. By the first call, it is not in the DOM yet, so it appends. In the later call, it is removed and re-added to the DOM, so effectively nothing happens.

If you want to append it multiple times, you need to clone it. In your case:

todoUl.appendChild(todoLi.clone(1)); // 1 = deep

If you just want to append li item, you probably don't want to clone/add the todoUl element in the subsequent calls.



Answered By - Jan TuroĊˆ
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing