I have a javascript file that sets an EventListener of \'click\' on every element with the tag. I want to get the id of the article clicked when
This mini javascript libary (1.3 KB) can do all these things
https://github.com/Norair1997/norjs/
nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);
This plugin can handle such stuff and more
Why is nobody mentioning a single event which checks for the clicked element?
document.body.addEventListener('click', function(e) {
var target = e.target;
if (target.nodeName === 'article') {
// do whatever you like ;-)
}
e.stopPropagation()
});
it's more performant to have less events..
if you don't need to check for click events on the whole body you could attach the event to some closer parent 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.
articles.addEventListener('click',redirect,false); // omit redirect(e) inside event listener // and then try with the alert as you did.
if does not work then try by e.id instead of e.target.id inside alert as below:
alert(this.id);
Thanks.
getElementsByTagName
returns a nodelist. You can then add an eventlistener to each one of those elements with a for loop.
<div id="test">
hey
</div>
<div id="test2">
yo
</div>
<script>
var nl = document.getElementsByTagName('div');
for(var i=0; i<nl.length; i++){
nl[i].addEventListener('click', function(e){
alert(e.target.id);
},false);
}
</script>
You are executing the redirect function instead of passing the reference, try this:
articles = document.getElementsByTagName('article');
articles.addEventListener('click',redirect,false);
function redirect(e){
alert(e.target.id);
}
Edit: Also, getElementsByTagName returns an array with articles, so you have to loop through them and call addEventListener on each one of them.
articles = document.getElementsByTagName('article');
for (var i = 0; i < articles.length; i++) {
articles[i].addEventListener('click',redirect,false);
}
function redirect(e){
alert(e.target.id);
}