Reputation: 3519
...
<tr>
<td>222</td>
</tr>
<tr>
<td>333 222</td>
</tr>
...
And I have this code for selector:
$("#TableName tr td:contains('222')");
Problem: I need to select the cell that the html is '222' only.
I try use $("#TableName td tr[html=222]")
but don't work.
Upvotes: 4
Views: 184
Reputation: 322452
You can use .filter()
instead to do an exact match.
var result = $("#TableName tr td").filter(function() {
return $.text([this]) === "222";
});
This uses $.text()
to compare the text value of the <td>
with "222"
. It's just a little quicker way of doing $(this).text()
. Gives you the same result. (Note that you need to pass this
in an Array [this]
.)
When there's a match, the element is returned into the resulting jQuery object.
If there's any possibility of leading or trailing white space in the <td>
, you can trim that with $.trim()
.
return $.trim( $.text([this]) ) === "222";
EDIT: You could create your own selector that will accomplish the same task if you want:
$.extend($.expr[':'], {
textIs: function(elem, i, attr) {
return ($.trim( $.text([elem]) ) === attr[3]);
}
});
var result = $("#TableName tr td:textIs(222)")
Upvotes: 5
Reputation: 66480
I found this implemenation of such selector (in comments in http://api.jquery.com/contains-selector/)
$.expr[":"].econtains = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}
Example:
$("div:econtains('john')").css({ color: "#F00" });
Upvotes: 0