Bip
Bip

Reputation: 697

Cannot read property 'length' of undefined

for (i = 0; i < count; i++) {
    var item = list.childNodes[i]._value;
    var RecID = item.RecID;
    var zerocount = 5 - RecID.length;
    var PicZeros = "";
    for (k = 0; k < zerocount; k++)
        PicZeros += "0";
    var url = "/p_" + PicZeros + RecID + "_01.jpg";
}

I get this error:

TypeError: Cannot read property 'length' of undefined 

I don't understand how to fix it?

Upvotes: 0

Views: 621

Answers (3)

user2404546
user2404546

Reputation:

try

`item.getAttribute('RECID')`

OR

place the <script> tag AFTER the <body>

like

<html> 
<body>
 </body>
<script>
</script>
 </html>

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881293

Well, at some point, list.childNodes[i]._value.RecID is giving you an undefined value.

That's the root cause of your problem and you need to fix it.

Perhaps count is wrong, perhaps you've populated the list badly, we can't really tell from the code given.

And, as an aside, I'm almost certain there's better ways to left-pad a string with 0 characters than with a loop. Something like:

var url = "/p_" + "00000".substring(RecID.length) + RecID + "_01.jpg";

would be better.

Upvotes: 2

Hilmi
Hilmi

Reputation: 3441

Try this

for (i = 0; i < count; i++) {
    var item = list.childNodes[i]._value;
    var RecID = item.RecID;
    if (RecID){
        var zerocount = 5 - RecID.length;
        var PicZeros = "";
        for (k = 0; k < zerocount; k++)
            PicZeros += "0";
        var url = "/p_" + PicZeros + RecID + "_01.jpg";
    }
}

Upvotes: 0

Related Questions