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 One Solution

Ru Song
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ru Song
Front End Web Development Techdegree Graduate 13,845 Points

ul tag name or ul class name

I was trying to add new item in ul with the code:

const newItem = document.createElement('li');

newItem.innerHTML = '<li><input>Hiking</li>';

ul.appendChild(newItem);

But it did not work. I dont know why I have to use list instead of ul to append a new item.

2 Answers

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

You can't add children to a ul directly. You need to save a reference to it in a variable. With this line (const ul = document.getElementsByTagName("ul")[0];) you save all uls on your page into an array and reference the very first item of an array(using [0]).

const newItem = document.createElement('li');

const ul = document.getElementsByTagName("ul")[0];

newItem.innerHTML = '<li><input>Hiking</li>';

ul.appendChild(newItem);

Your last statement is not authorized. newItem.innerHTML simply let u set the text content inside the new created li item. You can’t add anything to it.