Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble adding element with text to DOM tree

I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.

var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);

The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.

like image 372
Chris Trebi Avatar asked Feb 09 '26 22:02

Chris Trebi


2 Answers

This line

    var newEl = newEl.appendChild(newText); 

Change to

    newEl.appendChild(newText); 

When you reassign it its not the li anymore (this is not JQ)

like image 105
bresleveloper Avatar answered Feb 12 '26 15:02

bresleveloper


.appendChild returns the appended element. In this case your newEl will be a text node after this assignment.

var newEl = newEl.appendChild(newText);

You should remove the assignment and it is fine.

like image 45
Sefa Şahinoğlu Avatar answered Feb 12 '26 14:02

Sefa Şahinoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!