0

I'm trying to get the innerHTML of red font tags...

var fontTags = document.getElementsByTagName('font');
var reds = [];
var j = 0;
var i = 0; // ETA this line
for (i;i<=fontTags.length;i++) { // ETA the 'i<='
  if (fontTags[i].getAttribute('color') == 'RED') {
    reds[j] = fontTags[i].innerHTML;
    j++;
  }
}

The javascript console is informing me that "fontTags[i]" is undefined. I've tried no declaration, declaring with 'new Array()'... same thing. Help?

4
  • You are leaking a global i and really shouldn't use <font> tags at all. Commented Apr 27, 2012 at 9:31
  • If fontTags.length is larger than 0, fontTags.length will always evaluate to true. Hence, at some moment i will be (equal) larger than fontTags.length. You want to compare it against the current counter, like i < fontTags.length. Commented Apr 27, 2012 at 9:31
  • isn't your condition always true? and i will grow more than the number of elements in the nodeList, thus fontTags[i] will be undefined. Commented Apr 27, 2012 at 9:31
  • @ThiefMaster: It's for a Greasemonkey script ;) Commented Apr 27, 2012 at 9:43

3 Answers 3

4

Your for loop is missing a proper loop-condition.

for (i=0;i<fontTags.length;i++) {
    if (fontTags[i].getAttribute('color') == 'RED') {
        reds[j] = fontTags[i].innerHTML;
        j++;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Apologies. See edit for fixed code. I still see the same error, however.
it's what sirko wrote, but your condition is still in error. less than; and not less than or equal to.
Yes, because I'm starting at zero, and the length doesn't... duh. Thank you :)
0

for (i=0;i<fontTags.length;i++) {

check the for loop condition

Comments

0

use


for(i=0;i<fontTags.length;i++)

instead for (i=0;fontTags.length;i++)

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.