jQuery Custom Selector for selecting elements by exact text :textEquals
by Tim Banks
I needed a way to find labels based on the text that they contained. I thought about using :contains() for this, but in this particular case the text items I was searching on were names and I could have similar names that :contains() could incorrectly match on. For instance, if I was searching for “Banks, Tim” and there was an item with the text “Banks, Timothy” I would get both items returned. This is not the behavior I was looking for.
I decided to write a little custom selector to match on exact text. Here is the code for the custom selector:
$.expr[':'].textEquals = function(a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};
What is happening here is I am using a regular expression to test if the start and end of the element’s text matches the string passed in. Now I could search for the name “Banks, Tim” on a label element like this:
$("label:textEquals('Banks, Tim')");
Tags: HTML, dom, elements by text, jQuery
« Make Table Rows Sortable Using jQuery UI Sortable Linq Expressions on an Interface »
September 22nd, 2009 at 1:52 pm
[...] Lanit Development Blog – jQuery Custom Selector for selecting elements by exact text :textEqua… This entry was posted on Tuesday, September 22nd, 2009 at 6:52 am. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
January 8th, 2010 at 10:41 pm
how do I pass in a variable instead of a text string?
like this:
$(“li:textEquals(someVariable)”).css({”color” : ”red”});
January 8th, 2010 at 11:00 pm
$(“li:textEquals("+someVariable+")”).css({‘color’ : ‘red’});February 14th, 2011 at 3:34 am
Hi Luke,
Thanks for this neat solution ! I”m new to jquery and was amazed it wasn”t already out of the box.
Cheers
July 10th, 2011 at 5:27 pm
Thanks for posting this. It”s exactly what I was looking for!
March 7th, 2012 at 4:00 pm
Hi Luke,tank you so much for this code,it was great and you saved me.