Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if contains certain text, then run jquery

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

 <script>
 if ($('b:contains('Choose a sub category:')')) {

 $("td.colors_backgroundneutral").css("background-color","transparent");
 $("td.colors_backgroundneutral").children(':first-child').attr("cellpadding","0");
 };
 </script>
like image 434
user764728 Avatar asked Jun 10 '11 17:06

user764728


2 Answers

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
}
like image 136
Thomas Shields Avatar answered Oct 07 '22 12:10

Thomas Shields


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

if ($('b:contains("Choose a sub category:")').length > 0) { /*do things*/}
like image 39
dev4life Avatar answered Oct 07 '22 13:10

dev4life