3

Does anyone know if there's an equivalence selector in jQuery? Of course :contains exist, but what if we want exact matches?

My workaround is to do

$('a').filter(function() {
   return $(this).text() == myVar;
}).addClass('highlight');

But I was hoping of a much easier method of doing $('a:equals(' + myVar + ')').addClass('highlight') instead. Of course I could create the selector, but I'd have assumed something exists in the standard library.

Cheers

Kieran Senior
  • 17,960
  • 26
  • 94
  • 138

2 Answers2

3

There doesn't seem to be a pre-built selector for this but if I understand it correctly, you could register your own easily as :contentEquals or whatever.

Here is an example of how somebody implemented a regex filter selector.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

You'll need your own custom selector: There's a discussion about them here What useful custom jQuery selectors have you written?

Your custom selector might look something like:

$(document).ready(function() { 
    $.extend($.expr[':'], { 
        myEquivalence: function(el) { 
            return ($(el).val() == myVar);
        } 
    }); 
}); 
Community
  • 1
  • 1
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • Yup, I knew exactly this is what I was going to need as I had previously pointed out. Good to see an example though, thanks very much! – Kieran Senior Jan 06 '10 at 19:15