Foliotek Developer Blog

jQuery Custom Selector for selecting elements by exact text :textEquals

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')");