Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i think that the code is the same but i don't know why it make different results

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading