1 ...">

Get the text of the nth TD with all tr โ€‹โ€‹having a certain class

The code I'm working on is as follows:

<table> <tr class="warning"> <td> 1 </td> <td> name </td> <td> address </td> <td> phone no </td> <td> Location </td> </tr> <tr> <td> 3 </td> <td> name2 </td> <td> address2 </td> <td> phone no2 </td> <td> Location2 </td> </tr> <tr class="warning"> <td> 6 </td> <td> name5 </td> <td> address5 </td> <td> phone no5 </td> <td> Location5 </td> </tr> <tr> <td> 7 </td> <td> name6 </td> <td> address6 </td> <td> phone no6 </td> <td> Location6 </td> </tr> 

I like to get the text of the whole second TD with all tr โ€‹โ€‹with a class warning.

I tried using the _.each method but was not successful

+6
source share
4 answers

try it

 $('tr.warning').each(function(){ alert($(this).find('td').eq(1).text()); }); 

Demo here

+16
source

Try

 $('tr.warning td:eq(1)').text(); 

if you want a more specific answer than use :nth-child selector

 $('tr.warning td:nth-child(2)').text() 

http://jsfiddle.net/dbuZG/5/

+10
source

Using the jQuery :nth-child and .each() selector should work for you.

Fiddle: http://jsfiddle.net/chucknelson/KDy8X/

Jquery

 $(function() { //use the :nth-child selector to get second element //iterate with .each() $('table tr.warning td:nth-child(2)').each(function(index, element) { var name = $(element).html(); $('#name-list').append('<li>' + name + '</li>'); }); }); 

Some additional HTML:

 <div id="warning-names"> Warning Names: <ul id="name-list"> </ul> </div> 
+3
source

This will result in a list of names in the array:

 var names = $('tr.warning td:nth-child(2)').map(function() { return $(this).text(); }).get(); 

demo at http://jsfiddle.net/alnitak/CjQAh/

(use :eq(1) does not work because :eq is applied to the index in the entire set of returned elements, and not about the position of the element relative to its <tr> container, and therefore returns only one element).

+1
source

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


All Articles