Barrett Kuethen Barrett Kuethen - 7 months ago 30
HTML Question

How do I manipulate text on elements returned with jQuery find?

I'm new to jQuery, and maybe I'm going about this all wrong...

I need to select the nth td of every tr, do some math on it (divide the value by 60) and return the new value to the td.

$('#table tbody').find('tr td:eq(2)').text($(this).text() / 60);

<script src=""></script>

The jquery docs give examples of manipulating the css this way, so it seems like I'd be able to do that through .text() as well.

The console is not returning any errors, and also executes a console.log afterwards so I know it's continuing, but none of the values change in the DOM.

Should I be using .each() instead of .find()? Any help is appreciated.


You need to use a function argument to .text(). The function is called with the old value of the text as an argument, and the return value replaces it.

$('#table tbody').find('tr td:nth-child(2)').text(function(i, oldtext)
    return parseInt(oldtext)/60;

If you don't use a function, $(this).text()/60 is executed before calling text(), so it uses whatever this is in the calling context.

You also need to use :nth-child, not :eq, to access the third cell in each row. Otherwise, it just accesses the third cell in the entire result set.