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 trialTani Huang
6,952 PointsCan 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
231,269 PointsThe 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.