I have a javascript file that sets an EventListener of 'click' on every element with the <article>
tag. I want to get the id of the article clicked when the event fires. For some reason, my code produces nothing!
My javascript:
articles = document.getElementsByTagName('article');
articles.addEventListener('click',redirect(e),false);
function redirect(e){
alert(e.target.id);
}
Why isn't this working? BTW my article setup is in a function called when the window is loaded, and i know that works for sure because that function has other stuff that work.
EDIT
So i fixed my code so it will loop and add the listener to every article element, and now i get an alert box with nothing in it. When trying to output the e.target without the ID, i get the following message for every element:
[object HTMLHeadingElement]
Any suggestions?
ANOTHER EDIT
My current javascript code:
function doFirst(){
articles = document.getElementsByTagName('article');
for (var i = 0; i < articles.length; i++) {
articles[i].addEventListener('click',redirect(articles[i]),false);
}
}
function redirect(e){
alert(e.id);
}
window.addEventListener('load',doFirst,false);
This is showing my alert boxes when the page finished loading, without considering that i haven't clicked a damn thing :O
Adding an Event Listener to Multiple Elements Using a for...of Loop + IIFE. Open the console and click any of the buttons. The same event listener is added to each button using a for...of loop along with an immediately invoked function that passes the current element of the loop back into the function.
To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');
To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.
You are not passing an article object to redirect as a parameter.
Try this (EDIT):
articles = document.getElementsByTagName('article');
for (var i = 0; i < articles.length; i++) {
articles[i].addEventListener('click',redirect,false);
}
function redirect(ev){
alert(ev.target.id);
}
Hope, it will solve the bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With