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

Why is lis automatically updated after adding a new list item?

I have two questions about the teacher's code.

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

here , we selected ul to add the new list item. but we declared a similar variable at the top before const listUl = listDiv.querySelector('ul'); why don't we just use listUl here? it would be listUl.appendChild(li); it worked out fine I tried. Is there any reason behind not using this?

Another question is, I tried to track the lis variable during this addItemButton event. and I logged out lis like this

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

and I found lis is updated after this event. I totally confused. from my understanding it's been declared at the top as in the first place

const lis = listUl.children;

why is it automatically updated after we append a new list item to ul?

James Churchill
James Churchill
Treehouse Teacher

What course/workshop are you following along with?

@James Churchill I was following with JavaScript and the DOM which is where these snippets were from.

1 Answer

Guil Hernandez
STAFF
Guil Hernandez
Treehouse Teacher

Hi there Zhenghao He,

Sorry for the confusion. Sure, the listUl variable will also work. We wanted to show you how getElementsByTagName returns a collection, which is like an array, and you can access an element directly using its index. Also, selecting ul inside the callback makes the flow of the function a little easier to understand.

To answer your second question, .children returns a live HTMLCollection of child elements -- in this case all children of the ul. Changes in the DOM are reflected in the collection. When addItemButton.addEventListener(...) fires, an li element gets appended to the ul, which auto updates the collection.

Hope this helps. :)

thanks Guil. you da best