Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Adding and Removing Names Removing Names

John Bastian Bolhano
John Bastian Bolhano
4,800 Points

Why not use innerHTML instead of creating document.createElement?

li.textContent = text;
  const label = document.createElement('label');
  label.textContent = 'Confirmed';
  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  label.appendChild(checkbox);
  li.appendChild(label);
  ul.appendChild(li);

vs

li.innerHTML = `
    ${text}
    <label>
      Confirmed
      <input type='checkbox'>
    </label>
    <button>remove</button>
  `;
ul.appendChild(li);

4 Answers

Create an Element with document.createElement();

Your solution works whenever you just want to build up an object to insert into the document, but document.createElement() creates an object with a whole lot more methods which you could need when you want to modify your newly created element.

Construct an element with document.createElement(); in the console and take look at the methods on this object

Ben S
Ben S
5,638 Points

I agree with you, John. Using innerHTML is much more legible when combing through the code. I think Guil is using this other method as a continuation of what was taught in previous lessons on Treehouse.

Antti Lylander
Antti Lylander
9,686 Points

If there is already some content inside the tags you are inserting this new content it will be a problem with innerHTML as it will wipe everything. Now if you create a new element and nest it inside your tags, there is no problem with original content.

It just depends on what want to do. Probably the point of this video was just to make you aware of this method.

I might be wrong on this but as far as I have seen .innerHtml is used for editing the actual text or content inside of a set of tags. In this case the tags don't yet exist so we need to use document.createElement to create them.