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

Can Someone explain this in detail..please (var or let inside addEventListener or outside addEventListener)

<div class="container">
 <h1>Welcome</h1>
 <p>Hello welcome to my page.</p>
 <ul class="list reset">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
 </ul>
 <button class="btn">Start</button>
</div>

var btn = document.querySelector(".btn");

btn.addEventListener('click', () => {
  var ul = document.getElementsByTagName('ul')[0];
  var li = document.querySelector('li:last-child');
  ul.removeChild(li);
})
var btn = document.querySelector(".btn");
var ul = document.getElementsByTagName('ul')[0];
var li = document.querySelector('li:last-child');

btn.addEventListener('click', () => {
  ul.removeChild(li);
})

Why the second one only works once
Why the first one can keep removing

1 Answer

Steven Parker
Steven Parker
221,291 Points

The first example gets a new "li" each time you click, so it will always remove the last item.

The second one only sets "li" once, when the program first loads. So once you click and remove it, it never gets updated to select any of the remaining items.