marked-down
marked-down

Reputation: 10408

How to use .insertAfter on dynamic DOM elements with jQuery?

So I'm attempting to dynamically add a row to a table using jQuery's DOM creation tools, when I discovered that you cannot use the insertAfter() method on elements that have been dynamically created, rendering this:

var row = $('<tr></tr>')
  .append($('<td></td>', { html: firstVal })
      .insertAfter($('<td></td>', { html: secondVal  }) // This doesn't work!
      )
  );

useless, because that's exactly what I'm doing. Attempting to use insertAfter on a dynamic element.

What's the easiest and most effective solution to this which still produces clean code?

Upvotes: 0

Views: 2064

Answers (2)

Gosha_Fighten
Gosha_Fighten

Reputation: 3858

As far as I understand, you need to insert two cells in a row. You need to use both td elements in the append method.

<h2></h2>

    $(document).ready(function () {
    var row = $('<tr></tr>').append(($('<td></td>', { html: "test1" })), ($('<td></td>', { html: "test2" })));
    $("h2").append(row);
})

Upvotes: 1

Bergi
Bergi

Reputation: 664650

First of all, you can use insertAfter on dynamically created DOM elements. Only they need to have a parent node, so that there is a tree in which the "next" element could be inserted. You are calling insertAfter on that <td> before having it appended to the <tr>. The following would work:

var td1 = $('<td></td>', { html: firstVal }),
    td2 = $('<td></td>', { html: secondVal });

var row = $('<tr></tr>').append(td1);
td1.insertAfter(td2);

However, what you actually want to do is use append multiple times:

var row = $('<tr></tr>')
    .append($('<td></td>', { html: firstVal }))
    .append($('<td></td>', { html: secondVal }));

ot even with multiple arguments:

var row = $('<tr></tr>')
    .append($('<td></td>', { html: firstVal }),
            $('<td></td>', { html: secondVal }));

Upvotes: 2

Related Questions