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
Victor Luke
Courses Plus Student 82 PointsDon't understand the meaning of function(e)
Hi there! I've seen a Javascript program based on how to remove an element from DOM. But i'm feeling confused about the function.I don't understand the meaning of "e" parameter inside my function.I knew a parameter must have a value that's called argument but in my code where is my argument? Here is my codes
<script> document.querySelector('.divs').onclick=function(e){ var removeTarget=e.target.parentNode; removeTarget.parentNode.removeChild(removeTarget); };
</script>
2 Answers
Henrik Hansen
23,176 PointsThe parameter (e) is automatically passed from javascript to you function when you add an event listener. It represents the element that was affected, an example would be the button element that was clicked.
Victor Luke
Courses Plus Student 82 PointsThanks Thanks Thanks a lot Man!!!
Henrik Hansen
23,176 PointsGlad I could help. :)
Victor Luke
Courses Plus Student 82 PointsVictor Luke
Courses Plus Student 82 PointsThanks, You mean the value of "e" is the eventListner's value. That mean document.querySelector('.divs').onclick=e isn't it?
Henrik Hansen
23,176 PointsHenrik Hansen
23,176 Pointsdocument.querySelector('.divs') selects the element witch you add the onclick listener to. Then, when the event is triggered the function(e) is called, and JavaScript passes the element that triggered that event into (e). The document.querySelector('.divs').onclick is not really related to what happens in your function, it only sets the eventlistener to the selected element.
Victor Luke
Courses Plus Student 82 PointsVictor Luke
Courses Plus Student 82 PointsOkk,so what's the plan to add the "e" parameter inside the function? Is it only to make an object?
Henrik Hansen
23,176 PointsHenrik Hansen
23,176 PointsYes, it is an object from the event. You can access the clicked element with e.target
In your code you select several elements with the class 'divs', and set the same event listener to all of them. You could have used different functions to separate them, but now you have the (e), witch now is an object with info on what element was clicked, what the event was and some other stuff.
You do not have to use it or even add the (e) param to your function call, but in many cases it is very useful.