Chobbit
Chobbit

Reputation: 654

jQuery if div contains multiple text strings

I had a quick script to search for some text (a unique code) in a div and hide a different element if it exists:

var itemCode = ["000001"];

if( $(".itemCode").text().indexOf(itemCode) >= 0) {
  $(".codeBox").addClass("hideElement");
}

however I wanted to expand this so it finds one of multiple texts (codes) and if any of them exist then hide the element:

var itemCode = ["000001", "000003", "000008"];

if( $(".itemCode").text().indexOf(itemCode) >= 0) {
  $(".codeBox").addClass("hideElement");
}

and this isn't working. I'm sure It's probably something simple and I'm supposed to add a .each() somewhere but I'm just not getting it working when I experiment trying things, what am I missing?

Upvotes: 0

Views: 419

Answers (2)

Ben Morris
Ben Morris

Reputation: 282

Might be slighty quicker if you have a few item codes in your array

var itemCode = ["000001", "000003", "000008"];
var regExpPattern = itemCode.join('|');
if($(".itemCode").text().match(new RegExp(regExpPattern, 'i'))) {
 $(".codeBox").addClass("hideElement");
}
});

Upvotes: 2

Serge K.
Serge K.

Reputation: 5323

indexOf takes only one (mandatory) argument, so you'll have to iterate over your list to find element(s) matching your condition :

var itemCode = ["000001", "000003", "000008"];

var contains = itemCode.some(function(code) {
  return $(".itemCode").text().indexOf(code) >= 0;
});

if (contains) {
  $(".codeBox").addClass("hideElement");
}

Upvotes: 1

Related Questions