jQuery if “this” contains

前端 未结 4 687
予麋鹿
予麋鹿 2021-01-31 18:19

I\'m trying to change any elements containing a particular text string to a red color. In my example I can get the child elements to become blue, but there\'s something about th

相关标签:
4条回答
  • 2021-01-31 19:01

    I don't think there is a .contains function in jQuery. There is a .contains function but that function is used to see if a DOM element is a descendant of another DOM element. See documentation for .contains. (Credits to @beezir)

    I think you are looking for :contains selector. See below for more details,

    $('#main-content-panel .entry:contains("Replace Me")').css('color', 'red');
    

    http://jsfiddle.net/zatHH/1/

    0 讨论(0)
  • 2021-01-31 19:02

    I think we should convert our text to lower case. It is better to check with lowercase and uppercase.

    $('#main-content-panel .entry').each(function() {
        var ourText = $(this).text().toLowerCase(); // convert text to Lowercase
        if(ourText.match('replace me')) {
            $(this).css('color', 'red'); 
        }      
    });
    
    0 讨论(0)
  • 2021-01-31 19:11

    :contains is a selector. To check if a selector applies to given variable, you can use is:

    if($(this).is(':contains("Replace Me")')) 
    

    However Vega's solution is cleaner in this case.

    0 讨论(0)
  • 2021-01-31 19:20

    you can use match to find the text inside the particular element

    $('#main-content-panel .entry').each(function() {
        $(this).css('color', 'blue');      
    });			
    
    $('#main-content-panel .entry').each(function() {
        if($(this).text().match('Replace Me')) {
            $(this).css('color', 'red'); 
        }      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="main-content-panel">
        <div class="entry">ABC</div>
        <div class="entry">ABC Replace Me</div>
        <div class="entry">ABC</div>
        <div class="entry">ABC Replace Me</div>
    </div>

    0 讨论(0)
提交回复
热议问题