JQuery Selection Help

... <tr> <td>222</td> </tr> <tr> <td>333 222</td> </tr> ... 

And I have this code for the selector:

 $("#TableName tr td:contains('222')"); 

Problem: I need to select a cell in which only html has a value of "222".
I am trying to use $("#TableName td tr[html=222]") but it does not work.

+4
source share
2 answers

You can use .filter() instead for an exact match.

 var result = $("#TableName tr td").filter(function() { return $.text([this]) === "222"; }); 

$.text() used to compare the text value of <td> with "222" . This is just a little quick way to do $(this).text() . Gives you the same result. (Note that you need to pass this to Array [this] .)

When there is a match, the element returns to the jQuery result object.

If there is any possibility of a space or space in the <td> , you can trim with $.trim() .

 return $.trim( $.text([this]) ) === "222"; 

EDIT:. You can create your own selector that will perform 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)") 
+5
source

I found this implementation of such a selector (in the comments at 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" }); 
0
source

All Articles