Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

An alternate way to create the <li> elements?

Are there any significant difference between Guil's method of creating the <li> element (using document.createElement('li') and then the .appendChild() method) and mine?

const listHolder = document.getElementById('invitedList');
form.addEventListener('submit', (e) => {
  e.preventDefault();
  //My way: Create a 'li' variable and assign a string value of "<li>" together with the input value to it
  let li = "<li>" + input.value + "</li>";
  listHolder.innerHTML += li;
  input.value = '';
})

1 Answer

Steven Parker
Steven Parker
221,864 Points

Both methods create a new element on the page, but the original method creates a new element in the code. This allows other element methods to be called on it either before or after adding to the page. In the code shown above, "li" is just a string and cannot be used to reference the element itself.

If you're certain you don't need the other capabilities, either approach does the job. In fact, you can also eliminate the variable:

  listHolder.innerHTML += "<li>" + input.value + "</li>";

Thanks for the explanation!