简体   繁体   中英

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);

To create text node usedocument.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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM