How do I select a span containing a specific text value, using jquery?

JavascriptJquery

Javascript Problem Overview


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

<div>
   <span>FIND ME</span>
   <span>dont find me</span>
</div>

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Use contains:

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

Solution 3 - Javascript

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
        });
     }
}

Solution 4 - Javascript

I think this will work

var span;
$('span').each(function(){
  if($(this).html() == 'FIND ME'){
    span = $(this);
  }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMedicineManView Question on Stackoverflow
Solution 1 - JavascriptMalkView Answer on Stackoverflow
Solution 2 - JavascriptJake FeaselView Answer on Stackoverflow
Solution 3 - JavascriptTheWizardOfTNView Answer on Stackoverflow
Solution 4 - Javascriptbuck54321View Answer on Stackoverflow