0

So my ultimate goal is for the user to input three or more words, and then I must seperate the words, I.E if there are 4 words, I have to build 4 Rows with the word in each, I have been at it for hours and just can't figure out why the insertRow() method wont work, its telling me that "cannot call insertRow() method of undefined"

what I have in the else section of my conditional:

//build table around input
    var table=document.getElementById('myTable');


    for(i=0; i<2; i++)
    {
    table.insertRow(i);
    table.insertCell(i);}
1
  • 1
    create a demo in jsfiddle.net that replicates problem Commented Nov 1, 2013 at 1:26

3 Answers 3

1

The first problem I see is that you call .insertRow() on the table DOM object, but then you need to call .insertRow() on a row, not on the table. See MDN on insertCell for more details. Here's an example of some working code:

function addWords(e) {

    var str = document.getElementById("words").value;
    var words = str.split(/[\s,]/);
    if (words.length && words[0]) {
        //build table around input
        var table = document.getElementById('myTable');

        for (var i = 0; i < words.length; i++) {
            var row = table.insertRow(-1);
            var cell = row.insertCell(-1);
            cell.innerHTML = words[i];
        }
    }
}

And a working demo: http://jsfiddle.net/jfriend00/3g3Qy/

Sign up to request clarification or add additional context in comments.

Comments

0

You should call insertCell on a Row object.

var row = table.insertRow();
row.insertCell();

2 Comments

Do you have a table with id=myTable?
If you're running this script just before table is added to the DOM, it won't be able to find the table.
0

Put a console.log(table) after var table=.... If it prints undefined, the problem is that the script is running too soon and you'll need to move the script to the very bottom of the page, or wait for the DOM to load.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.