Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get last 'td' containing some text without using each

I have a table in below format,

<table>
  <tr>
    <td>Dynamic Text1</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>Dynamic Text2</td>
  </tr>
  <tr>
    <td>Dynamic Text3</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>

I want to get the last td containing something other than just a &nbsp;. In the example markup shown this would be Dynamic Text3, but I will not know the specific text in advance. This is simply possible by running in a loop but, is there any way to do this without using each?

like image 934
moustacheman Avatar asked Dec 07 '22 07:12

moustacheman


2 Answers

Update:

$('td').filter(function(){
    return !!$.trim($(this).text());
}).last().css('color', 'red');

Demo: Fiddle

like image 114
Arun P Johny Avatar answered Dec 08 '22 21:12

Arun P Johny


This should work now

var td = $('table td:last');

function findTD() {
    if (!td.text().replace(/\u00a0/g, "").length) {
        if (td.parent().is(':not(:first)')) {
            td = td.parent().prev().find('td');
            return findTD();
        } else {
            return 'No text found!';
        }
    } else {
        return td.text();
    }
}

alert(findTD());

FIDDLE

like image 41
Spokey Avatar answered Dec 08 '22 19:12

Spokey