+ 2
Event delegation in JavaScript Developer I Exam - How to detect a click?
I am preparing for the Salesforce JavaScript Developer I certification and came across this question in the Pass4Future JavaScript Developer I Exam practice test. I am stuck on how to check if a specific element (myElement) was clicked. Here's the code snippet: document.body.addEventListener('click', (event) => { if (/* answer here */) { console.log('myElement clicked'); } }); What is the correct condition to put inside the if statement so it logs when only myElement is clicked? Would love some help understanding how event delegation works in this context!
3 odpowiedzi
+ 5
Danielle Lee Welcome to sololearn
Just use this:
if (event.target === myElement)
Basically, you're telling JS, “Hey, only react if myElement was actually clicked.” Since you're using event delegation on body, this helps you catch clicks but still keep it specific.
Simple and clean.
+ 3
You can check if the event target has a certain id:
event.target.id == ...
https://sololearn.com/compiler-playground/WtV7jl8Exh21/?ref=app
0
Lisa Yes, but only if the element has an ID, though if it doesn't it's still possible to use any of className, classList, name, etc, which are unique enough.