I have a table in below format,
<table>
<tr>
<td>Dynamic Text1</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Dynamic Text2</td>
</tr>
<tr>
<td>Dynamic Text3</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
I want to get the last td
containing something other than just a
. 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
?
I have a table in below format,
<table>
<tr>
<td>Dynamic Text1</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Dynamic Text2</td>
</tr>
<tr>
<td>Dynamic Text3</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
I want to get the last td
containing something other than just a
. 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
?
-
4
I don't think so, You need to use
.filter()
which will internally iterate through the elements – Arun P Johny Commented Jun 10, 2013 at 13:05 - Have you tried the :contains selector – wirey00 Commented Jun 10, 2013 at 13:06
-
$('td:contains("Dynamic Text 3")')
– Niccolò Campolungo Commented Jun 10, 2013 at 13:06 - xpath selector? be aware that xpath is not supported by one and only one browser (guess 3 times which). – Kyslik Commented Jun 10, 2013 at 13:08
- 2 As you can see from the bunch of "wrong" answers, you did not ask a clear question. You really need to work on asking questions! – epascarello Commented Jun 10, 2013 at 13:38
6 Answers
Reset to default 6Update:
$('td').filter(function(){
return !!$.trim($(this).text());
}).last().css('color', 'red');
Demo: Fiddle
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
UPDATE This doesn't cover OP needs, mis understood OP's question
Use :contains selector :
http://jsfiddle/NkYZf/2
var search = "Dynamic Text3";
$('table td:contains("'+search +'"):last').css('color','red');
You can use :contains
var lastTd = $('td:contains("' + text + '"):last');
Here is a possible POJS solution
HTML
<table>
<tr>
<td>Dynamic Text1</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Dynamic Text2</td>
</tr>
<tr>
<td>Dynamic Text3</td>
</tr>
<tr>
<td> </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);
On jsfiddle
$("td").filter(function() { return $.text([this]) == 'Dynamic Text3'; })
.addClass("red");