Reputation: 125
I am creating some anchor <a>
tags on the fly with Javascript.
Whenever any user clicks on one of these links I want the the background colour of the tag to change.
I am creating the <a>
links on the fly like this:
var link = document.createElement("a");
link.href = newstr;
var linktext = document.createTextNode(count);
link.appendChild(linktext);
I am getting all the links on the page by using:
document.onclick=function() {
var a_array = document.getElementsByTagName("a");
console.log(a_array.length);
}
This gives me the total number of links but I want to know which element has been clicked. I have tried using the this
keyword but did get the wanted indformation. I think I am using it wrong.
I do not want to use jQuery.
Any alternate code to target the currently clicked link will also help.
Upvotes: 0
Views: 3353
Reputation: 2090
Since you have the jQuery tag on your post, an alternate solution that may work is:
JS:
$('body').on('click', 'a', function(){
$(this).css('background','red');
});
Upvotes: 0
Reputation: 122906
You seem to try using event delegation (assigning the click handler on document level). In that case you need to know where the click originated. event
is your friend here:
document.onclick = function(e) {
e = e || event;
var from = e.target || e.srcElement;
if (/a/i.test(from.tagName)) {
from.style.backgroundColor = 'red';
}
}
The jQuery way of delegating would be: removed, OP needs no jQuery. He/she may be right
Here's a jsFiddle with a bit more code do demonstrate the usefulness of event delegation
Upvotes: 3
Reputation: 24
If the op creates the links dynamically, ie:
var a = document.createElement('a');
Then all he needs to do is set the link handler at that point:
var a = document.createElement('a');
a.onclick = function()
{
this.style.backgroundColor = "red";
return false; //stop the click from navigating somewhere.
}
a.href = newstr;
Which will add the same handler to all dynamically created links - right where he creates them.
It's a matter of which links he needs to recognize - if it's all links, then he might have to getElementsByTagName, as well as the code above for dynamic links.
Upvotes: 0