jQuery Custom Selector for selecting elements by exact text :textEquals

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

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

4 Responses to “jQuery Custom Selector for selecting elements by exact text :textEquals”

  1. jQuery Custom Selector for selecting elements by exact text :textEquals | Tim Banks Says:

    […] 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. […]

  2. Rodney Says:

    how do I pass in a variable instead of a text string?

    like this:

    $(“li:textEquals(someVariable)”).css({‘color’ : ‘red’});

  3. Iain Says:

    Hi Luke,
    Thanks for this neat solution ! I’m new to jquery and was amazed it wasn’t already out of the box.
    Cheers


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: