开发者

How do loop through a table to select a specific table cell on each row using jquery?

开发者 https://www.devze.com 2023-03-15 05:20 出处:网络
I am trying to place text in the 6th table cell of each row of my table. But all I am getting is the first row selected:

I am trying to place text in the 6th table cell of each row of my table. But all I am getting is the first row selected:

$('tbody tr:even t开发者_如何学编程d:eq(5)').each(function(){
                $(this).text('$145');
            });

What adjustment do I need to make?


I think that the following should work:

$('tbody tr').each(
function(){
    $(this).find('td:eq(5)').text('$145');
});

JS Fiddle demo.

Reference:

  • each()
  • find()
  • :eq() selector
  • text()


$( 'table tr' ).each( function() {

  $(this).find( 'td' ).eq(5).text('$145');

});

UPDATE

Since the accepted anwser does the same thing but using the :eq() selector instead of the .eq() method, it's worth reading the additional notes on the jQuery DOCs for the eq selector:

Because :eq() is a jQuery extension and not part of the CSS specification, queries using :eq() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").eq(index) instead.

So I think it's advisable to use the .eq() method instead of the :eq() selector.

0

精彩评论

暂无评论...
验证码 换一张
取 消