最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I select a span containing a specific text value, using jquery? - Stack Overflow

programmeradmin14浏览0评论

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

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

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

<div>
   <span>FIND ME</span>
   <span>dont find me</span>
</div>
Share Improve this question asked Feb 24, 2012 at 2:11 MedicineManMedicineMan 15.3k33 gold badges103 silver badges154 bronze badges 1
  • possible duplicate of jquery find element by text – Felix Kling Commented Feb 24, 2012 at 3:17
Add a comment  | 

4 Answers 4

Reset to default 143

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

Use contains:

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

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

I think this will work

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

评论列表(0)

  1. 暂无评论