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
Ben Crabtree
8,297 PointsWhy document.createElement('li') and not element.innerHTML += '<li>' + input.value + '</li>'?
Before watching the video on .createElement(), I decided to try adding a list item to the list using .innerHTML (See below), which had the same result as appending the li created using .createElement() did. Why use .createElement over .innerHTML?
const newItemButton = document.querySelector('button.new-item');
const newItemInput = document.querySelector('input.new-item');
const listToAddItemTo = document.querySelector('ul');
newItemButton.addEventListener('click', () => {
listToAddItemTo.innerHTML += '<li>' + newItemInput.value + '</li>';
});
1 Answer
Christopher Debove
Courses Plus Student 18,373 PointsThe two methods work.
With document.createElement function you're creating a element object. With it you can add event listener on it, add css properties, and other many things the API permits you.
You can't do that with appending the element via "innerHTML" method (without selecting the element after)
Ben Crabtree
8,297 PointsBen Crabtree
8,297 PointsThanks Christopher!
That makes sense, .createElement() gives you more flexibility in terms of what you can add to/do with an element initially without having to reselect the element.