2

I want to use jQuery 1.3.2 in an html file and create a dynamic table. For this, I create the first row, then create a for loop running 10 times and in each iteration, I select the last row of the table and use after() to add a new row after it. This new row contains the value of the counter of my for loop.

code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Document</title>
<script type="text/javascript" src="../jquery-1.3.2.js"></script>
<script type="text/javascript">

    $("document").ready(function() {
        for (var i = 0; i < 11; i += 1) {
            var newItem = $("<tr><td>"i"</td></tr>");
            $("#table1 tr:last").after(newItem.html());
        }
    });

</script>

</head>
<body>
<table id="table1">
    <tr>
    <td>row 1 col 1</td>
    </tr>
</table>
</body>
</html>

The problem is, only the first row that was created in <table></table> is displayed. Please help out.

3 Answers 3

6
$("#table1 tr:last") 

selects the last row. It's a bit more expensive in terms of processing needed compared to

$("#table1")

which selects just the entire table.

$("#table1 tr:last").after(...)

is expensive again, because after you selected the last row, you take one step back, get back to the parent of tr:last and try to append something.

Why not try appending table rows as children of table like this?

var row = $("<tr><td>"i"</td></tr>");
$("#table1").append(row);

Append will always add at the end of the children of table1. This should be faster. Take a look at append in the jQuery documentation.

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

Comments

4
for (var i = 0; i < 11; i += 1) {
    $("#table1").append("<tr><td>" + i + "</td></tr>");
}

Here is my code

Comments

0

Try this way:

var newItem = "<tr><td>" + i + "</td></tr>"; 
$("#table1 tr:last").after(newItem);

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.