'How do I prevent textContent from overwriting the dynamically created span?

So I'm trying to insert an element into the list but the span keeps getting overwritten by the textcontent that I'm giving to li. This is what the code is supposed to look like:

<li class="togglable"><span class="plus-sgn">+</span> Add Task</li>

This is what I'm getting:

<li class="togglable">Add Task</li>

And here's the code:

  const togglable = document.createElement('li');
  const span = document.createElement('span');
  togglable.className = 'togglable';
  span.className = 'plus-sgn';
  span.textContent = '+';
  togglable.appendChild(span);
  togglable.textContent = 'Add Task';
  taskList.appendChild(togglable);


Solution 1:[1]

To create text node use document.createTextNode:

function add() {
  const togglable = document.createElement('li');
  togglable.className = 'togglable';

  const span = document.createElement('span');
  span.className = 'plus-sgn';
  span.textContent = '+';
  togglable.appendChild(span);

  //append text as text node
  togglable.appendChild(document.createTextNode('Add Task'));

  taskList.appendChild(togglable);
}

add();
add();
add();
<ul id='taskList'>
  <li>Abc</li>
</ul>

Solution 2:[2]

Maybe you can add it as follow:

const taskList = document.querySelector('ul#taskList');
const togglable = `<li class="togglable"><span class="plus-sgn">+</span> Add Task</li>`;

taskList.innerHTML += togglable;
<ul id="taskList"></ul>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 the Hutt
Solution 2 prettyInPink