0

i'm trying to add a list element to an existing ul using a function from an onclick like this:

<span style="color:red;">Bob</span>

If i hard code it in the HTML it works fine:

<ul id="LsUL">
<li><span style="color:blue;">Joe</span></li>
<li><span style="color:green;">Frank</span></li>
</ul>

But using a function it dose not work

function changeText2() {
  var entry = document.createElement('li');
  entry.appendChild(document.createTextNode('<span style="color:red;">Bob</span>'));
  document.getElementById("LsUL").appendChild(entry);
}
changeText2();
<ul id="LsUL">
  <li><span style="color:blue;">Joe</span></li>
  <li><span style="color:green;">Frank</span></li>
</ul>

The output should be like this:

  • Joe (blue)
  • Frank (green)
  • bob (red)

But I get this:

Joe (blue)
Frank (green)
<span style="color:red;">bob</span>

I cant seem to get it to work any ideas? Thanks.

1
  • 1
    createTextNode inserts text, not HTML. Try insertAdjacentHTML instead Commented Mar 22, 2020 at 8:11

1 Answer 1

4

createTextNode will do exactly what it sounds like - create a text node. Whatever you pass in, it will always create a text node, composed only of text - it won't create child elements.

Element nodes can contain text nodes, but not the other way around - text nodes can't contain anything but text.

If you want to set the new li's HTML, use innerHTML:

var entry = document.createElement('li');
entry.innerHTML = '<span style="color:red;">Bob</span>';
list.appendChild(entry);

You can also do it all at once with insertAdjacentHTML:

list.insertAdjacentHTML('beforeend', '<li><span style="color:red;">Bob</span></li>');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much i looked all over for an answer!

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.