Jquery: Checking to see if div contains text, then action

后端 未结 7 1261
野趣味
野趣味 2020-11-28 06:47

I\'m trying to check in jQuery if a div contains some text, and then add a class if it does.

So I wrote something like this:

    if( $(\"#field >          


        
相关标签:
7条回答
  • 2020-11-28 06:54

    Why not simply

    var item = $('.field-item');
    for (var i = 0; i <= item.length; i++) {
           if ($(item[i]).text() == 'someText') {
                 $(item[i]).addClass('thisClass');
                 //do some other stuff here
              }
         }
    
    0 讨论(0)
  • 2020-11-28 06:59

    Ayman is right but, you can use it like that as well :

    if( $("#field > div.field-item").text().indexOf('someText') >= 0) {
            $("#somediv").addClass("thisClass");
        }
    
    0 讨论(0)
  • 2020-11-28 07:01

    Your code contains two problems:

    • The equality operator in JavaScript is ==, not =.
    • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

    I suggest the following instead:

    if ($('#field > div.field-item:contains("someText")').length > 0) {
        $("#somediv").addClass("thisClass");
    }
    
    0 讨论(0)
  • 2020-11-28 07:04

    Here's a vanilla Javascript solution in 2020:

    const fieldItem = document.querySelector('#field .field-item')
    fieldItem.innerText === 'someText' ? fieldItem.classList.add('red') : '';
    
    0 讨论(0)
  • 2020-11-28 07:08

    Yes, I now made think for me. And it works fine!!!

    if($("div:contains('CONGRATULATIONS')").length)
                            {
                                $('#SignupForm').hide(500);
                            }
    
    0 讨论(0)
  • 2020-11-28 07:17

    You might want to try the contains selector:

    if ($("#field > div.field-item:contains('someText')").length) {
        $("#somediv").addClass("thisClass");
    }
    

    Also, as other mentioned, you must use == or === rather than =.

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