Salesforce Certified JavaScript Developer free question 5 / 10 · Domain 3: Browser and Events
A page contains this markup. <ul id="menu"><li><span id="label">Home</span></li></ul> A developer attaches one listener to the list and clicks the span. const menu = document.getElementById('menu'); menu.addEventListener('click', (e) => { console.log(e.target.tagName, e.currentTarget.tagName); }); document.getElementById('label').click(); What is logged?
- LI UL, because target is the closest list item above the clicked element
- UL UL, because the two properties refer to the element that owns the running listener
- SPAN SPAN, because the two properties refer to the innermost element that was clicked
- SPAN UL, because target is the clicked element and currentTarget holds the listener
Show the answer and explanation
Answer: D
Why this is correct
target refers to the element on which the event was initially fired, which is the span. currentTarget refers to the element to which the running handler is attached, which is the ul. While the event bubbles, target stays the same and currentTarget changes.
Why the other options are wrong
"UL UL, because the two properties refer to the element that owns the running listener" … Only currentTarget refers to the element with the listener. target stays on the element where the event was fired.
"SPAN SPAN, because the two properties refer to the innermost element that was clicked" … currentTarget changes as the event travels. During the listener on the list it is the list.
"LI UL, because target is the closest list item above the clicked element" … target is the element on which the event was initially fired, which is the span itself and not one of its ancestors.
Key points
In a delegated listener, use target to find what was clicked and currentTarget to refer to the element that holds the listener.