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: , , ,

« »

6 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. Luke Daffron Says:
    
    $(“li:textEquals("+someVariable+")”).css({‘color’ : ‘red’});
    
  4. 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

  5. Bobby Says:

    Thanks for posting this. It”s exactly what I was looking for!

  6. vesna Says:

    Hi Luke,tank you so much for this code,it was great and you saved me.

Leave a Reply

NoFollow Plugin made by Web Hosting