Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Javascript for loop not looping

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);​

Answer*

Draft saved
Draft discarded
Cancel
7
  • 1
    Don't put quotes around the onclick function. Commented Mar 5, 2012 at 16:33
  • 1
    This: link.setAttribute('onclick', function(){ alert("Okay") }); is incorrect. OP was doing it correctly. The 'alert("Okay");' gets automatically wrapped in a function. Commented Mar 5, 2012 at 16:52
  • 1
    @Rocket: It's setting an attribute, not a property, so either way it's getting the .toString() treatment. Commented Mar 5, 2012 at 16:53
  • 1
    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... Commented Mar 5, 2012 at 17:01
  • 1
    @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? Commented Mar 5, 2012 at 17:03

lang-js

AltStyle によって変換されたページ (->オリジナル) /