The node element is deleted only the second time, and those created using the add function are deleted the first time
function move(o) {
var parent = o.parentNode;
parent.removeChild(o);
parent.insertBefore(o, parent.firstChild);
}
function add() {
var node = document.createElement('li');
var textnode = document.createTextNode("new");
node.appendChild(textnode);
node.setAttribute("onclick", "move(this)");
document.getElementById("table").appendChild(node);
id = "myList"
}
function del() {
o = document.getElementById("table");
o.removeChild(o.firstChild);
}
<ol id='table'>
<li onclick="move(this)">1</li>
<li onclick="move(this)">2</li>
<li onclick="move(this)">3</li>
<li onclick="move(this)">4</li>
<li onclick="move(this)">5</li>
<li onclick="move(this)">6</li>
</ol>
<button onclick="add()">Append</button> <button onclick="del()">Del</button>
You have to use
o.removeChild(o.firstElementChild);
in your del() function.
So this is the updated code:
<ol id="table">
<li onclick="move(this)">1</li>
<li onclick="move(this)">2</li>
<li onclick="move(this)">3</li>
<li onclick="move(this)">4</li>
<li onclick="move(this)">5</li>
<li onclick="move(this)">6</li>
</ol>
<button onclick="add()">Append</button> <button onclick="del()">Del</button>
<script>
function move(o) {
var parent = o.parentNode;
parent.removeChild(o);
parent.insertBefore(o, parent.firstChild);
}
function add() {
var node = document.createElement("li");
var textnode = document.createTextNode("new");
node.appendChild(textnode);
node.setAttribute("onclick", "move(this)");
document.getElementById("table").appendChild(node);
id = "myList";
}
function del() {
o = document.getElementById("table");
o.removeChild(o.firstElementChild);
}
</script>
The firstChild is not an LI but a textnode
Use
o.removeChild(o.firstElementChild);
Also delegate the click
const table = document.getElementById("table")
table.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.tagName==="LI") {
move(tgt);
}
})
function move(o) {
var parent = o.parentNode;
parent.removeChild(o);
parent.insertBefore(o, parent.firstElementChild);
}
function add() {
var node = document.createElement('li');
var textnode = document.createTextNode("new");
node.appendChild(textnode);
table.appendChild(node);
}
function del() {
table.removeChild(table.firstElementChild);
}
<ol id='table'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ol>
<button onclick="add()">Append</button> <button onclick="del()">Del</button>