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);
Didier Ghys
30.6k9 gold badges77 silver badges82 bronze badges
asked Mar 5, 2012 at 16:29
ccarnley7
4414 gold badges10 silver badges20 bronze badges
2 Answers 2
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);
answered Mar 5, 2012 at 16:31
Sarfraz
384k81 gold badges561 silver badges613 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
gen_Eric
Don't put quotes around the
onclick function.ccarnley7
Oh, my bad on the quotes around "read_today". Thanks for the catch! However, loop still does not appear to be looping because no events are being attached to the links...
|
try this:
if(link.href.indexOf("read_today") != -1)
answered Mar 5, 2012 at 16:32
Tom
4,1702 gold badges26 silver badges40 bronze badges
Comments
lang-js
link.setAttribute('onclick', 'alert("Okay")');<<< this is NOT how you attach events.read_todaya variable? Should it be'read_today'?