#I need help adding an eventlistener to a link inside of a div element!

16 messages ยท Page 1 of 1 (latest)

royal sapphire
#

๐Ÿ™Œ๐Ÿป

I am trying to figure out how i can add an eventlistener to a <a> tag, but the <a> tag don't have a class. There are more than one <a> tag on the page, so i figured a for loop is needed. What i do have is a class on the parent <div> element. I can make one link work, but not all of them.

I have attached an image of the code.
All help/tips are greatly appreciated!๐Ÿ”ฅ ๐Ÿ™๐Ÿผ

elder whale
#

Hey! I'm new but I'd like to help.
Can you share a screenshot of the HTML as well?
Is there a reason you can't/don't want to add an id to the link?

#

And what about the e.target?

amber basin
#

You don't even need that. If you know there's only 1 <a> tag and only one div with the artdeco-entity-lockup__title class, you can use querySelector, like this:

const nameBtn = document.querySelector('.artdeco-entity-lockup__title a');
royal sapphire
#

For more detail - im working on a chrome extension that adds an element to a specific page, though i can't render the new element before a link is pressed. Because it's not my site i can't add a class to the link(a tag) and therefor i figured i could use the parent div which does have a class.

There are in total 24 links on the page, so hopefully this could be done with some sort of loop, instead of repeating the code. I have tried a couple of different things, but turning the child of the parent div (the a tags) into an array seemed like the best option. The thing is - now i can't add an eventlistener to all children (all a tags)

elder whale
#
document.querySelector('div.class').addEventListener('click', (e) => {
    console.log(e.target);
})
amber basin
#

2 secs, I'll put something together for you

royal sapphire
#

Thank you so much!

amber basin
royal sapphire
#

Thank you very much for taking the time, appreciate it alot!

#

Though i got this error in the console

#

I adjusted one thing - sorounded the everything in a function in order to call it at the top