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 Interacting with the DOM Traversing the DOM Getting All Children of a Node with children

Samuel Kleos
seal-mask
.a{fill-rule:evenodd;}techdegree
Samuel Kleos
Front End Web Development Techdegree Student 13,728 Points

Why can't I add a button to the <li> before adding text content to the same <li>? See my snapshot.

Here is my snapshot: https://w.trhou.se/qohzirpvk9

Please consider this button creation function which adds a button to a list item:

function addBtnRemove(li) {
    let btnRemove = document.createElement('button');
    btnRemove.className = 'remove';
    btnRemove.textContent = "Remove";
    li.appendChild(btnRemove);
}

If I add the btnRemove function after the li.textContent = input.value; the button appears on the newly created list item just fine:

btnCreate.addEventListener('click', () => {
  const input = document.querySelector('.input-main');
  let ul = document.getElementsByTagName('ul')[0];

  let li = document.createElement('li');
  li.textContent = input.value;
  addBtnRemove(li);
  ul.appendChild(li);
  input.value = '';
});

However, If I add the btnRemove function before li.textContent = input.value; the button doesn't appear:

btnCreate.addEventListener('click', () => {
  const input = document.querySelector('.input-main');
  let ul = document.getElementsByTagName('ul')[0];

  let li = document.createElement('li');
  addBtnRemove(li);
  li.textContent = input.value;
  ul.appendChild(li);
  input.value = '';
});

Why?

1 Answer

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey Samuel, thanks for your question! This essentially comes down to the use of .textContent. .textContent replaces the contents of that HTML DOM element.

By calling addBtnRemove(li) before line 48, you're:

  • appending a button to li
  • and then changing it's content to [your string here] Essentially the button is wiped by using .textContent

By calling addBtnRemove(li) AFTER line 48, you're:

  • changing li's contents to [your string here]
  • appending a button to li Therefore both will appear because we added the button after changing the content

I hope this helps!