views:

385

answers:

3

What is wrong with this code?

var divarray = [];
var articleHTML = [];
var absHTML;
var keyHTML;
var bodyHTML = [];
var i = 0;
divarray = document.getElementById("yui-main").getElementsByTagName("div");
for ( var j in divarray) {
    if(divarray[i].className == "articleBody"){
        articleHTML = divarray[i];
        for( var k in articleHTML ){
            bodyHTML[i] = '';
            if(articleHTML[i].className == "issueMiniFeature"){continue;}
            if(articleHTML[i].className == "abstract"){absHTML = articleHTML[i]; continue;}
            if(articleHTML[i].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
            bodyHTML[i] = articleHTML[i];
        }
        break;
    }
    i++;
}

The error I get is:

TypeError: Cannot read property 'className' of undefined

I am using Google Chrome.

A: 

Did you mean:

var divarray = [];
var articleHTML = [];
var absHTML;
var keyHTML;
var bodyHTML = [];
var i = 0;
divarray = document.getElementById("yui-main").getElementsByTagName("div");
for ( var j in divarray) {
    if(divarray[j].className == "articleBody"){
        alert("found");
        articleHTML = divarray[j];
        break;
    }
    bodyHTML[i] = '';
    if(divarray[j].className == "issueMiniFeature"){continue;}
    if(divarray[j].className == "abstract"){absHTML = divarray[j]; continue;}
    if(divarray[j].className == "journalKeywords"){keyHTML = divarray[j]; continue;}
    bodyHTML[i] = divarray[j];
    i++;
}
sirhc
forget it, I will just open a new question with updated code.
Arlen Beiler
+1  A: 

You initialize articleHTML as an array, then you're apparently setting articleHTML to an HTMLElement (divarray[i]) but then treating it like an array (articleHTML[i]) — this actually tries to get the i property of the HTMLElement that you pulled out of divarray, which doesn't exist, and then you try to get the className of this undefined value.

Chuck
+2  A: 

You're using a very strange loop.

 for (var j in array) {
    // use array[i]
    ++ i
 }

The problem is .getElementsByTagName doesn't return an array, but an array-like interface. For example:

>>> for (var j in document.getElementsByTagName('body')) console.log(j)
0
length
item
namedItem

Therefore, in your for/in loop, i will go up to array.length + 2 instead of array.length - 1. Since array[array.length + 2] does not exist, it will return undefined and throw the error when you try to access a property of it.


Just always use

for (var i = 0, len = array.length; i < len; ++ i) {
  ...
}

with arrays.

KennyTM
I deleted my original answer once I noticed how bizarre the code was.
ChaosPandion
I meant that to be a foreach. My, I am all mixed up today!
Arlen Beiler
I later found out that I had the right idea, but was doing it wrong.
Arlen Beiler