简体   繁体   中英

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 );

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++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM