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 trialhb8
5,660 PointsFailed to execute 'removeChild' on 'Node
If i declare the variables ul & li outside the addEventListener, removing li only works once. If i declare the variables inside of addEventlistener everything works. can someone help me understand ?
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="remove">remove</button>
<ul id="ul">
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
<script>
var ul = document.getElementsByTagName('ul')[0];
var li = document.querySelector('li:last-child');
remove.addEventListener('click', ()=>{
ul.removeChild(li);
});
</script>
</body>
</html>
3 Answers
Steven Parker
231,269 PointsGlad I could help. Happy coding!
Steven Parker
231,269 PointsThe code outside the event handler is executed only once, but the code inside the handler is executed each time the button is clicked.
So when done outside, "li" represents the the last list item of the freshly-loaded page, and once that item is removed it continues to reference the removed item.
But when done inside, each time the button is pushed "li" is set the last list item at that time, so you can continue to remove items.
hb8
5,660 PointsThanks Steven, that clarifies it :)