Module 5, Pumpkin's Perrfect Meme Picker, searching by e.target.id

Hi there!
Nothing urgent, just wondering :slight_smile:

e.target already contains the element on which the event happened, why we search it again?

const someElement = document.getElementById(e.target.id)

Can’t we just use (if needed):

const someElement = e.target

Or if we only need the ID:

const elementID = e.target.id

Of for the parent element:

const parent = e.target.parentElement

Hey @Oleg_II,

document.getElementById(e.target.id) and e.target effectively references the same DOM element when used in an event listener context where e is the event object passed to the event handler function. If the context is correct, the direct use of e.target should be preferred for simplicity and performance.

I think you may be referring to this code in the Scrim lesson document.getElementById(e.target.id).parentElement.classList.add('highlight')? Writing it as e.target.parentElement.classList.add('highlight') would still work I’m pretty sure.

Correct me if I’m wrong here @Tom_Chant!

Hey @Oleg_II

I agree with what @roku said. And what I think you’re getting at is that in the meme picker project:

document.getElementById(e.target.id).parentElement.classList.add('highlight')

Would do the same thing as:

e.target.parentElement.classList.add('highlight')

Although the way I did it was longer, I felt it was a bit easier to read that way and felt more natural. Tbh, it’s very much matter of opinion though and fine to do it the second way. If I were going to use an element or the event more in that function I would definitely store it in a const for clarity.

Hope that helps! If I misunderstood your question, do get back to me!

1 Like

Hi @Tom_Chant!
Thanks for replying.
Like your Essential JavaScript concepts lessons - well thought, interesting and with a lot of “muscle memory” training :slight_smile:
Understood your explanation about clarity. Just was a bit confused - why searching for the element if we already have it in event object itself? :slight_smile:
Agree with storing the element in const for clarity too, that make sense.

Actually, it can be even destructured from the event object with some other properties if needed (also within the callback event parameter):

someInputEl.addEventListener('change', ( { target } ) => {...
// or
const { name, target, value } = e

PS By the way, how you guys achieve “@some_name” when addressing to someone? I tried clicking on names and went to the profiles… Had to copy/pase then :laughing:

@Oleg_II

I just type @ and then a list appears, and after writing the first few letters it narrows it down to the person I want to reply to :slight_smile:

That restructuring way is also cool. I do think the cognitive load of reading it is a bit higher than the other ways though. I am splitting hairs tbh :laughing: