Gustavo Martínez
Gustavo Martínez

Reputation: 67

How I can solve Object has no method 'appendChild'

my problem is that when you run the code in the console shows this: object has no method 'appendChild'

This is my code:

    function createColumns() {

    var nodesTr = document.getElementsByTagName( 'tr' );

    for( var i in nodesTr ) {

        if( i < 3 || i == 8 || i == 13 || i == 15 || i == 18 )
            continue;

        for( var j = 1; j <= 14; j++ ) {

            var nodeHTML = document.createElement( 'td' );
            nodeHTML.innerHTML = 1;
            nodesTr[ i ].appendChild( nodeHTML );

        }   // end for

    }   // end for

} // end function createColumns

the problem is in this part

nodesTr[ i ].appendChild( nodeHTML );

Upvotes: 0

Views: 70

Answers (1)

cookie monster
cookie monster

Reputation: 10972

It's because you're using for-in instead of a for statement

This will hit properties that are not nodes:

for( var i in nodesTr ) {

You can verify this by using console.log() to log your values.

console.log(i, nodesTr[ i ]);

I believe it will hit the .length property, and perhaps the .item() method.


Using a for statement will only iterate numeric indices, and will guarantee that the order is what you defined in the loop.

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

Upvotes: 5

Related Questions