0

I am trying to select a span with specific text in jquery. Jquery "contains" is not very strict, so if I use it and search for "tab", it would also select "table", which I dont want.

$(".spanbox:contains('Tab')").css('background-color', 'Green')

The example-spans:

<span class="spanbox">Tab</span>
<span class="spanbox">Table</span>

Is there a way to exclusively select on of the classes members with a certain text?

villeroy
  • 65
  • 1
  • 1
  • 8

2 Answers2

3

You can do it using .filter() with a function parameter, like so:

$(".spanbox").filter(function() {
   return $(this).text() == 'Tab';
}).css('background-color', 'Green');
Nelson
  • 49,283
  • 8
  • 68
  • 81
1

try this way :

$.fn.textEquals = function (text) {
    var match = false;
    $(this).each(function () {
        if ($(this).text().match("^" + escapeRegex(text) + "$")) {
            match = true;
            return false;
        }
    });
    return match;
};

$(".spanbox").textEquals('Tab').css('background-color', 'Green');
$(".spanbox").textEquals('Table').css('background-color', 'Red');
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111