0

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);​
4
  • 4
    link.setAttribute('onclick', 'alert("Okay")'); <<< this is NOT how you attach events. Commented Mar 5, 2012 at 16:31
  • 2
    Is it entering the function? do you have an error message? Have you checked the length of the list? Commented Mar 5, 2012 at 16:31
  • Is read_today a variable? Should it be 'read_today'? Commented Mar 5, 2012 at 16:32
  • read_today is undefined, apparently Commented Mar 5, 2012 at 16:33

2 Answers 2

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);​
Sign up to request clarification or add additional context in comments.

7 Comments

Don't put quotes around the onclick function.
This: link.setAttribute('onclick', function(){ alert("Okay") }); is incorrect. OP was doing it correctly. The 'alert("Okay");' gets automatically wrapped in a function.
@Rocket: It's setting an attribute, not a property, so either way it's getting the .toString() treatment.
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...
@user1250254: Have you tested the .length of the a elements returned? alert(links.length);? Are you running your script before the elements have been loaded into the page?
|
1

try this:

if(link.href.indexOf("read_today") != -1) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.