0

I am using GreaseMonkey to recolor certain elements of a specific website. However, when using the loops below, only the first loop makes any changes. Changing the order that the loops are in will allow only the first loop to have effect.

var i;
var evenRows = document.getElementsByClassName("even");
for (i=0;i<=evenRows.length;i++) { evenRows[i].style.backgroundColor = '#555'; }

var oddRows = document.getElementsByClassName("odd");
for (i=0;i<=oddRows.length;i++) { oddRows[i].style.backgroundColor = '#333'; }

var theLinks = document.getElementsByTagName("a");    
for (i=0;i<=theLinks.length;i++)  { theLinks[i].style.color = '#aaa'; }
floopa
  • 3
  • 1
  • 1
    wouldn't it make more sense to just change the style rule itself? making `.even { background-color: #555}` would be a lot easier than having to loop on every .even element. – Marc B Aug 26 '14 at 18:32
  • Yes that would be ideal, but I don't have access to the original code of the site. That's why I'm using Greasemonkey to stylize, after the fact. The same way that I make the SO site have a black background. – floopa Aug 26 '14 at 18:36
  • @floopa You can't use [GM_AddStyle](http://stackoverflow.com/questions/19385698/how-to-change-a-class-css-with-a-greasemonkey-script)? – JLRishe Aug 26 '14 at 18:48
  • Thanks for that comment. Sort of a GM novice. I'll have a look – floopa Aug 26 '14 at 18:56

1 Answers1

0

The problem is with your loop logic, which is throwing a JS error. The array is 0 indexed, but the length property is 1 indexed. In your loop you are looking checking to see if your counter is less than or equal to the length of the array, which means that the loop will still run when i is equal to the evenRows.length. You cannot access evenRows[evenRows.length] because it does not exist.

Change i <= evenRows.length; to i < evenRows.length; and this works nicely.

JS fiddle: http://jsfiddle.net/grammar/vdwxua7s/1/

grammar
  • 871
  • 10
  • 22
  • Thanks grammar. Maybe we should change your name to "syntax". GM wasn't showing me JS errors. – floopa Aug 26 '14 at 18:50