").append($("").text("one")) .appen...">

How to get the nth child in jquery of a new element

I created a table 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 set the click events on some of the tableRow cells created above. For this purpose I want to use the nth child selector. However, from the documentation, it seems that it can be used with some selectors, for example:

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

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

+4
source share
4 answers

I want to use the nth child selector for this purpose.

In this case, you can use .find()

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

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

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

Or in this case you can use . children () what could be better

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

Try with .eq() as

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

Or you can directly call from tableRow, for example

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

You created the element dynamically, so you need to use the following structure if it is statically created (i.e. created in HTML, you can use what you mentioned for ul)

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

Demo

0
source

Source: https://habr.com/ru/post/1487799/


All Articles