0

To add li element in ul I have done this...

var ul = document.getElementById('ul-id');
var li= document.createElement("li");
li.appendChild("some text here");
ul.appendChild(li);

But its giving error in my console. I am not getting what is the problem with this code. Any help will be appreciated.

Error:

Error: NotFoundError: DOM Exception 8
code: 8
message: "NotFoundError: DOM Exception 8"
name: "NotFoundError"
stack: "Error: An attempt was made to reference a Node in a context where it does not exist.

Thanks!

1 Answer 1

2

Because appendChild() expects a dom element reference as the parameter. You are passing a string as the value to the appendChild(), instead pass a text node

li.appendChild("some text here"); should be

li.appendChild(document.createTextNode("some text here"));

Demo: Fiddle

or

li.innerHTML = "some text here2";

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.