0

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?

1
  • if (itemCode.length >= 0) Commented Feb 21, 2018 at 11:03

2 Answers 2

2

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");
}
});
Sign up to request clarification or add additional context in comments.

3 Comments

This worked great thanks, could you explain the .join('|') part please so I can understand how it's working? Thanks again
The join function joins an array of strings into one string using an optional divider in this case "|". The pipe is used like an or operator within regular expressions. So thisvalue|orthisone. regular-expressions.info/alternation.html w3schools.com/jsref/jsref_join.asp
Thanks this has helped a lot :)
1

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");
}

1 Comment

Thanks for the further explanation of indexOf, this also worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.