Stephanie Parker
Stephanie Parker

Reputation: 401

Javascript createElement and append child node

I'm trying to create an element and append a child node to it, but my return is just a string without the element.

I'm first creating the element with

const li = document.createElement('li');

Secondly, I'm creating the text node with:

const text = document.createTextNode('hello');

Finally I'm appending the text to the li with:

const newMessage = li.appendChild(text);

Results for console.log(newMessage) is just a string of the message. Output in the dom is just a string also. I'm expecting the complete li element with the text node. I've also tried using innerHTML instead of appendChild.

Seems like a huge noob question but I'm not sure what I'm missing?

Thanks,

Upvotes: 1

Views: 3624

Answers (3)

jo_va
jo_va

Reputation: 13964

You have to append your li into the DOM for it to appear. You can do it by querying a parent element and using appendChild on it:

document.querySelector('ul').appendChild(li);

The appendChild function returns the node that was just appended. In your case, newMessage will be the text node appended to your li, see the MDN appendChild doc.

const li = document.createElement('li');
const text = document.createTextNode('hello');
const newMessage = li.appendChild(text);

document.querySelector('ul').appendChild(li);

console.log(newMessage);
<ul></ul>

Upvotes: 1

Mamun
Mamun

Reputation: 68933

Node.appendChild()

Return value

The returned value is the appended child except when the given child is a DocumentFragment, in which case the empty DocumentFragment is returned.

You do not need to assign the li.appendChild in a variable:

const li = document.createElement('li');
const text = document.createTextNode('hello');
li.appendChild(text);
console.log(li.appendChild(text).nodeName); // #text
document.querySelector('ul').appendChild(li);
<ul></ul>

Upvotes: 1

ellipsis
ellipsis

Reputation: 12152

Append the li element to the dom too, to show it.

const li = document.createElement('li');
const text = document.createTextNode('hello');
var a=li.appendChild(text);
document.getElementById("list").appendChild(li)
console.log(a)
<ul id="list">
</ul>

Upvotes: 2

Related Questions