Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!