maximus
maximus

Reputation: 4302

How to get nth child in jquery of a new element

I have created table row using jquery:

var tableRow = $("<tr>").append($("<td>").text("one"))
                        .append($("<td>").text("two"))
                        .append($("<td>").text("three"));

Now I add it to the table in the document:

$("#table_id").append(tableRow);

The next thing I want to do is to set the click events on some of the cells of the tableRow created above. I want to use nth child selector for that purpose. However from the documentation it seems that it is possible to use it with some selectors like :

$("ul li:nth-child(2)")

But now I need to use :nth-child() for a variable tableRow. How is it possible?

Upvotes: 4

Views: 15557

Answers (4)

techfoobar
techfoobar

Reputation: 66663

I want to use nth child selector for that purpose.

In that case, you can use .find()

cell = tableRow.find(':nth-child(2)');
cell.on('click', function() {
    ...
});

Upvotes: 14

Thirumalai murugan
Thirumalai murugan

Reputation: 5906

Your created the element dynamically so you have to use the following structure, if its statically created(ie: created in HTML you can use what your mention for ul)

$('#table_id').find(":nth-child(2n)")

DEMO

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .find() along with nth-child

tableRow.find('td:nth-child(2)')

Or in this case you can use .children(), which might be better

tableRow.children('nth-child(2)')

Upvotes: 2

GautamD31
GautamD31

Reputation: 28763

Try with .eq() like

 $("#table_id tr td:eq(1)")

Or you can directly call from tableRow like

$(tableRow + "tr td:eq(1)")

Upvotes: 0

Related Questions