Code don't work, can't read property 'className' of undefined
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 == "ab开发者_高级运维stract"){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.
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.
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.
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++;
}
精彩评论