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 JavaScript and the DOM (Retiring) Making Changes to the DOM Appending Nodes

Edwin Carbajal
Edwin Carbajal
4,133 Points

Not a question but something I added that Guil missed

If the text input is an empty string clicking the button adds an empty node to the page. I fixed this with the following:

addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  if (addItemInput.value.length > 0) {
   li.textContent = addItemInput.value;
   ul.appendChild(li); 
  }
  addItemInput.value = '';
});

First I check if the inputs value is greater than 1. If it is then I add append it to the page. I did the same for the descriptionButton event listener :)

1 Answer

Steven Parker
Steven Parker
229,786 Points

:point_right: You'll find many opportunities to enhance the samples in the videos.

In some videos, the instructor will even invite you to add more to the project as an exercise for yourself.

Your idea to omit the addition when the content is empty is a very good enhancement :+1:, but why not wrap the entire routine in the conditional and also omit the other unnecessary code lines?

addItemButton.addEventListener('click', () => {
  if (addItemInput.value.length > 0) {
    let ul = document.getElementsByTagName('ul')[0];  // used only to add a new element
    let li = document.createElement('li');  // only create the element if it will be added
    li.textContent = addItemInput.value;
    ul.appendChild(li);
    addItemInput.value = '';  // this is not needed if the value is already empty
  }
});
Edwin Carbajal
Edwin Carbajal
4,133 Points

Good points!, Thanks Steven!