Why does the code make difference output and it is almost the same input?
Input:
var Add = document.getElementById('AddElement'); //the button
var Element = document.getElementById('element'); // the input text
var ListParent = document.querySelector('ul');
Add.addEventListener('click', function(){
var AddText = document.createElement('li').appendChild(document.createTextNode("hello"));
ListParent.appendChild(AddText);
})
Output:
first click:
hello
second click:
hellohello
Input:
var Add = document.getElementById('AddElement');
var Element = document.getElementById('element');
var ListParent = document.querySelector('ul');
Add.addEventListener('click', function(){
var AddText = document.createElement('li');
AddText.appendChild(document.createTextNode('hello'));
ListParent.appendChild(AddText);
})
Output:
first click:
- hello
second click:
- hello
- hello
>Solution :
appendChild returns the appended node:
const div = document.createElement('div');
const parent = document.createElement('div');
const result = parent.appendChild(div);
console.log(result === div);
So when you do
var AddText=document.createElement('li').appendChild(document.createTextNode("hello"));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The value put into addText is the created text node. In contrast, with
var AddText = document.createElement('li');
it’s the <li>, not the text node.
So, with the first approach, the created <li> doesn’t get used (and probably isn’t what you want).
If you wanted to use the <li>, and slim your code down, assign to the .textContent of the <li> instead.
Add.addEventListener('click', function(){
ListParent.appendChild(document.createElement('li'))
.textContent = element.value;
})