if contains certain text, then run jquery

前端 未结 3 803
执笔经年
执笔经年 2021-01-04 04:23

I need to run a jquery only if the bold element contains particular text. What am I doing wrong?

 

        
相关标签:
3条回答
  • 2021-01-04 04:50

    Besides using single quotes inside single quotes, which breaks the string, you're using a jQuery selector inside an if statement. This selector only filters your b tags to those which contain "Choose a sub category"; and then returns a list of those elements. It does not return a boolean. Instead, use the .contains() method, like so:

    if($("b").contains("Choose a sub category")) {
       // do stuff 
    }
    

    You can read more here

    EDIT: since the .contains() method appears to be deprecated, here's a pure JS solution:

    var el = document.getElementById("yourTagId") // or something like document.getElementsByTagName("b")[0] if you don't want to add an ID.
    if (el.innerHTML.indexOf("Choose a sub category") !== -1) {
        // do stuff
    }
    
    0 讨论(0)
  • 2021-01-04 04:52
     if ($("b").has(":contains('Choose a sub category:')").length) { 
     /*Your Stuff Here*/
     }
    
    0 讨论(0)
  • 2021-01-04 04:56

    I have always used this to determine if an element exists:

    if ($('b:contains("Choose a sub category:")').length > 0) { /*do things*/}
    
    0 讨论(0)
提交回复
热议问题