-1

I have a very long conditional statement like the following: How to shorten condition statements in Javascript?

var str = document.getElementsByClassName("label");
for(var i = 0; i<str.length; ++i){
if(str[i].innerHTML === "US" || str[i].innerHTML === "VN"|| str[i].innerHTML === "War"...){
str[i].style.display = "none";}}
Hau Nguyen
  • 21
  • 1
  • 4
  • 1
    Don't think this warrants an answer as the question may be better suited for http://codereview.stackexchange.com/ but: `if (['US', 'VN', 'War', ...].includes(str[i].innerHTML))` – noahnu Dec 03 '16 at 04:58

4 Answers4

0

Use Includes , includes is supported in es6

var values = ["US","VN","War"];
if (values.includes(str[i].innerHTML)){

}

You can do it with indexOf(..)>-1 :

var values = ["US","VN","War"];
if (values.indexOf(str[i].innerHTML)>-1){

}
Alon
  • 2,919
  • 6
  • 27
  • 47
0

You can use array with indexOf or includes.

Note: includes will work on ES6 supported browsers

Working snippet:

var str = document.getElementsByClassName("label");
var options = ['US', 'VN', 'War'];

for(var i = 0; i<str.length; ++i){
   var text = str[i].innerHTML;
   if(options.indexOf(text) !== -1){
      str[i].style.display = "none";
   }
}
<span class="label">US</span>
<span class="label">USA</span>
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

Testing via a regular expression makes it pretty short:

if (/^(US|VN|War|etc)$/.test(str[i].innerHTML)) {

In context:

var str = document.getElementsByClassName("label");
var re = /^(US|VN|War|etc)$/;
for (var i = 0; i < str.length; ++i) {
    if (re.test(str[i].innerHTML)) {
        str[i].style.display = "none";
    }
}

If required you can make it a case-insensitive test by adding the i flag to the regex:

var re = /^(US|VN|War|etc)$/i;
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

This can be done using jquery by selecting all elements with class label then filtering them by checking that their innerHTML is within the array ['US','VN'] and for all that satisfy the filter condition, we change the css style display

$(".label").filter(function (){
        return ['US','VN'].includes(this.innerHTML);
   }).css("display","none");
Aimee Borda
  • 842
  • 2
  • 11
  • 22