Foliotek Development Blog

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

« »

7 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. Brian Says:

    Maybe you should have given credit where it was due:
    http...@googlegroups.com/msg09829.html
    Nice function though.

  7. Rob Says:

    I found a specific case that it didn”t work (children(“”) selector.. can”t pin down the exact case why it is failing). So I made a slight modification:
    $.expr['':''].textEquals = function (a, i, m) {
    return $(a).text() === m[3];
    };

    Since it”s just comparing and not RegExing, it probably will be a little quicker too

Leave a Reply