74

How do I find the span containing the text "FIND ME"

<div>
   <span>FIND ME</span>
   <span>dont find me</span>
</div>
MedicineMan
  • 15,008
  • 32
  • 101
  • 146
  • possible duplicate of [jquery find element by text](http://stackoverflow.com/questions/7321896/jquery-find-element-by-text) – Felix Kling Feb 24 '12 at 03:17

4 Answers4

142

http://api.jquery.com/contains-selector/

$("span:contains('FIND ME')")

ETA:

The contains selector is nice, but filtering a list of spans if probably quicker: http://jsperf.com/jquery-contains-vs-filter

$("span").filter(function() { return ($(this).text().indexOf('FIND ME') > -1) }); -- anywhere match
$("span").filter(function() { return ($(this).text() === 'FIND ME') }); -- exact match
Malk
  • 11,855
  • 4
  • 33
  • 32
  • 2
    does that answer my next question? http://stackoverflow.com/questions/9424509/how-do-i-select-a-span-containing-an-exact-text-value-using-jquery – MedicineMan Feb 24 '12 at 02:27
  • 1
    Yes. Filter is the answer again, but this time you check the entire .text() value for a match instead of looking for the index. Answer updated. – Malk Feb 24 '12 at 02:31
  • 1
    Thanks Malk! I hadn't heard of filter(). Sometimes it's necessary as contains() is a wildcard comparison so will find 'FIND ME' and 'DON'T FIND ME' which isn't helpful if you need an exact match – Peadar Jan 14 '13 at 11:17
10

Use contains:

$("span:contains('FIND ME')")
Jake Feasel
  • 16,785
  • 5
  • 53
  • 66
  • This does not work. In the OP he has two spans: `find me`, and `dont find me`. You are checking if the span contains this text so you found both. – Paul Apr 09 '21 at 21:10
4

By the way, if you'd like to use this with a variable, you'd do it this way:

function findText() {
    $('span').css('border', 'none');  //reset all of the spans to no border
    var find = $('#txtFind').val();   //where txtFind is a simple text input for your search value
    if (find != null && find.length > 0) {
        //search every span for this content
        $("span:contains(" + find + ")").each(function () {
            $(this).css('border', 'solid 2px red');    //mark the content
        });
     }
}
TheWizardOfTN
  • 161
  • 10
3

I think this will work

var span;
$('span').each(function(){
  if($(this).html() == 'FIND ME'){
    span = $(this);
  }
});
buck54321
  • 847
  • 9
  • 21