JQuery: Get the last 'td' containing text without using each

I have a table in the format below,

<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 latest td containing something other than simple &nbsp; . In the example of the markup shown, this will be Dynamic Text3 , but I will not know the specific text in advance. It is just possible while working in a loop, but is there a way to do this without using each ?

+4
source share
6 answers

Now it should work

 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

+4
source

Update:

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

Demo: Fiddle

+6
source

UPDATE This does not apply to OP needs, OP misunderstood question

Usage: contains a selector:

http://jsfiddle.net/NkYZf/2

 var search = "Dynamic Text3"; $('table td:contains("'+search +'"):last').css('color','red'); 
+4
source

You can use :contains

 var lastTd = $('td:contains("' + text + '"):last'); 
+2
source

Here is a possible POJS solution

HTML

 <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> 

Javascript

 var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, function (node) { if (node.tagName === "TD" && node.textContent.trim()) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_SKIP; }, false); while (treeWalker.nextNode()) {} console.log(treeWalker.currentNode !== document.body ? treeWalker.currentNode : null); 

Jsfiddle on

0
source
 $("td").filter(function() { return $.text([this]) == 'Dynamic Text3'; }) .addClass("red"); 
-1
source

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


All Articles