Reputation: 441
I have some code that I'm working on for my work. We're trying to loop through all the links on our page and automatically add an onclick event. However, the loop doesn't appear to be "looping" at all. Could somebody please help?
var ourdomainname = "ourdomain.com";
function linkallthelinks(domain) {
var links = document.getElementsByTagName("a");
for (i = 0; i < links.length; i++) {
var link = links[i];
var href = link.getAttribute("href");
if (href.indexOf(read_today) != -1) {
link.setAttribute('onclick', 'alert("Okay")');
}
}
}
//function call
linkallthelinks(ourdomainname);
Upvotes: 0
Views: 1311
Reputation: 382666
Missing quotes here:
if(href.indexOf(read_today) != -1)
Should be:
if(href.indexOf('read_today') != -1)
Overall, this is what you should have:
var ourdomainname = "ourdomain.com";
function linkallthelinks(domain) {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var link = links[i];
var href = link.getAttribute("href");
if (href.indexOf('read_today') != -1) {
link.setAttribute('onclick', 'alert("Okay")');
}
}
}
//function call
linkallthelinks(ourdomainname);
Upvotes: 2