Programmatically construct a condition for use in an if() statement












32














Let's assume for a moment that I have something like this:



if (document.getElementById('div1').innerHTML &&
document.getElementById('div2').innerHTML &&
document.getElementById('div3').innerHTML &&
document.getElementById('div4').innerHTML &&
document.getElementById('div5').innerHTML &&
...
document.getElementById('div100').innerHTML)


Obviously typing out and maintaining a big conditional statement like this is problematic.



I would like some solution like:



var conditional = "";
for(var i = 1; i <= 100; i++){
conditional += "document.getElementById('div" + i +"').innerHTML";
if(i < 100) {
conditional += " && ";
}
}
if(interpretStringAsJSExpression(conditional)){
console.log("all my divs have content");
}


Is something like this possible in JavaScript?



Great answers have been submitted, and I am sure that I and others will benefit from them. However, purely from a place of curiosity, is it possible to store and run JavaScript expressions or commands in strings?



Like I have proposed in my example: interpretStringAsJSExpression(conditional)










share|improve this question




















  • 5




    You can execute a string with eval(conditional). It's almost always the wrong solution, though.
    – Barmar
    Dec 9 '18 at 3:38












  • Maybe you are interested in Array.prototype.every
    – Bakuriu
    Dec 9 '18 at 14:57






  • 2




    I approve of your curiosity.
    – Joshua
    Dec 9 '18 at 21:39
















32














Let's assume for a moment that I have something like this:



if (document.getElementById('div1').innerHTML &&
document.getElementById('div2').innerHTML &&
document.getElementById('div3').innerHTML &&
document.getElementById('div4').innerHTML &&
document.getElementById('div5').innerHTML &&
...
document.getElementById('div100').innerHTML)


Obviously typing out and maintaining a big conditional statement like this is problematic.



I would like some solution like:



var conditional = "";
for(var i = 1; i <= 100; i++){
conditional += "document.getElementById('div" + i +"').innerHTML";
if(i < 100) {
conditional += " && ";
}
}
if(interpretStringAsJSExpression(conditional)){
console.log("all my divs have content");
}


Is something like this possible in JavaScript?



Great answers have been submitted, and I am sure that I and others will benefit from them. However, purely from a place of curiosity, is it possible to store and run JavaScript expressions or commands in strings?



Like I have proposed in my example: interpretStringAsJSExpression(conditional)










share|improve this question




















  • 5




    You can execute a string with eval(conditional). It's almost always the wrong solution, though.
    – Barmar
    Dec 9 '18 at 3:38












  • Maybe you are interested in Array.prototype.every
    – Bakuriu
    Dec 9 '18 at 14:57






  • 2




    I approve of your curiosity.
    – Joshua
    Dec 9 '18 at 21:39














32












32








32







Let's assume for a moment that I have something like this:



if (document.getElementById('div1').innerHTML &&
document.getElementById('div2').innerHTML &&
document.getElementById('div3').innerHTML &&
document.getElementById('div4').innerHTML &&
document.getElementById('div5').innerHTML &&
...
document.getElementById('div100').innerHTML)


Obviously typing out and maintaining a big conditional statement like this is problematic.



I would like some solution like:



var conditional = "";
for(var i = 1; i <= 100; i++){
conditional += "document.getElementById('div" + i +"').innerHTML";
if(i < 100) {
conditional += " && ";
}
}
if(interpretStringAsJSExpression(conditional)){
console.log("all my divs have content");
}


Is something like this possible in JavaScript?



Great answers have been submitted, and I am sure that I and others will benefit from them. However, purely from a place of curiosity, is it possible to store and run JavaScript expressions or commands in strings?



Like I have proposed in my example: interpretStringAsJSExpression(conditional)










share|improve this question















Let's assume for a moment that I have something like this:



if (document.getElementById('div1').innerHTML &&
document.getElementById('div2').innerHTML &&
document.getElementById('div3').innerHTML &&
document.getElementById('div4').innerHTML &&
document.getElementById('div5').innerHTML &&
...
document.getElementById('div100').innerHTML)


Obviously typing out and maintaining a big conditional statement like this is problematic.



I would like some solution like:



var conditional = "";
for(var i = 1; i <= 100; i++){
conditional += "document.getElementById('div" + i +"').innerHTML";
if(i < 100) {
conditional += " && ";
}
}
if(interpretStringAsJSExpression(conditional)){
console.log("all my divs have content");
}


Is something like this possible in JavaScript?



Great answers have been submitted, and I am sure that I and others will benefit from them. However, purely from a place of curiosity, is it possible to store and run JavaScript expressions or commands in strings?



Like I have proposed in my example: interpretStringAsJSExpression(conditional)







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 9 '18 at 7:57









Peter Mortensen

13.5k1983111




13.5k1983111










asked Dec 9 '18 at 3:03









WillD

439114




439114








  • 5




    You can execute a string with eval(conditional). It's almost always the wrong solution, though.
    – Barmar
    Dec 9 '18 at 3:38












  • Maybe you are interested in Array.prototype.every
    – Bakuriu
    Dec 9 '18 at 14:57






  • 2




    I approve of your curiosity.
    – Joshua
    Dec 9 '18 at 21:39














  • 5




    You can execute a string with eval(conditional). It's almost always the wrong solution, though.
    – Barmar
    Dec 9 '18 at 3:38












  • Maybe you are interested in Array.prototype.every
    – Bakuriu
    Dec 9 '18 at 14:57






  • 2




    I approve of your curiosity.
    – Joshua
    Dec 9 '18 at 21:39








5




5




You can execute a string with eval(conditional). It's almost always the wrong solution, though.
– Barmar
Dec 9 '18 at 3:38






You can execute a string with eval(conditional). It's almost always the wrong solution, though.
– Barmar
Dec 9 '18 at 3:38














Maybe you are interested in Array.prototype.every
– Bakuriu
Dec 9 '18 at 14:57




Maybe you are interested in Array.prototype.every
– Bakuriu
Dec 9 '18 at 14:57




2




2




I approve of your curiosity.
– Joshua
Dec 9 '18 at 21:39




I approve of your curiosity.
– Joshua
Dec 9 '18 at 21:39












7 Answers
7






active

oldest

votes


















19














As the other answers said, you can solve your conditions problem more easily.



But, to answer your new question




purely from a place of curiosity, is it possible to store and run
JavaScript expressions or commands in strings?




Yes, you can write JavaScript code to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.






share|improve this answer



















  • 1




    Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
    – WillD
    Dec 9 '18 at 4:42



















25














You can do the tests in a loop.



var allOK = true;
for (var i = 1; i <= 100; i++) {
if (!document.getElementById("div"+i).innerHTML) {
allOK = false;
break;
}
}
if (allOK) {
console.log("all my divs have content");
}


You could also give all your DIVs a common class, then use a built-in iterator.



var allDivs = document.getElementsByClassName("divClass");
if (Array.from(allDivs).every(div => div.innerHTML)) {
console.log("all my divs have content");
}





share|improve this answer























  • I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
    – Gaurav
    Dec 9 '18 at 3:10






  • 1




    @Gaurav An empty string is falsey.
    – Barmar
    Dec 9 '18 at 3:11










  • +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
    – billynoah
    Dec 9 '18 at 3:27






  • 1




    Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
    – BlueRaja - Danny Pflughoeft
    Dec 9 '18 at 13:43












  • You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
    – Dev
    Dec 10 '18 at 3:52



















8














Why interpret a string of code? There are other means like for loops:



var conditionResult = true;
for(var i = 1; conditionResult && (i < 101); i++) {
conditionResult = conditionResult && document.getElementById('div' + i).innerHTML;
}

if(conditionResult) {
// Do something here
}


The for loop condition conditionResult && (i < 101) will break the loop once conditionResult is determined to be falsy; no need to keep looping in this case.



You can also use array methods like some and every if you have the elements in an array:



var arr = [/* array of DOM elements */];

var conditionResult = arr.every(elem => elem.innerHTML); // This is equivalent to (innerHTML && innerHTML && ...)

var conditionResult = arr.some(elem => elem.innerHTML); // This is equivalent to (innerHTML || innerHTML || ...)





share|improve this answer































    2














    You can set condition to true and check each one, setting condition to false and break out of the loop if any are false.



    var conditional = true;
    for(var i = 1; i <= 100; i++){
    if (!document.getElementById('div' + i).innerHTML) {
    condition = false;
    break;
    }
    }





    share|improve this answer





























      2














      Use document.querySelectorAll for this type of operation






      // Get all the divs that have ids which start with div
      var theDivs = document.querySelectorAll('[id^="div"]');
      var i,l,el,divsWithContent = ;

      // Loop through all theDivs
      l = theDivs.length;
      for(i = 0; i < l; i++) {
      // el is the div
      el = theDivs[i];

      // Test to make sure the id is div followed by one or more digits
      if (/^divd+$/.test(el.id)) {
      // If the div has something in it other than spaces, it's got content
      if (el.textContent.trim() !== "") {
      // Save the divs with content in the array
      divsWithContent.push(el.id);
      }
      }
      }

      // Show the results
      document.getElementById("result").textContent = divsWithContent.join("n");

      <h1>Div test</h1>
      <div id="div1">This</div>
      <div id="div2">that</div>
      <div id="div3"></div>
      <div id="div4">and</div>
      <div id="div5">the other thing</div>
      <h2>Divs with content</h2>
      <pre id="result"></pre>





      Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll






      share|improve this answer





























        1














        You could just store the document.getElementById('divXX').innerHTML items in an array, and then, just use



        items.reduce((a, b) => a && b);


        That way, you can change individual div elements in your expression without having to re-created the whole list






        share|improve this answer



















        • 2




          It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
          – Jörg W Mittag
          Dec 9 '18 at 14:14










        • @JörgWMittag: it would. but I've seen few languages where you can write this
          – blue_note
          Dec 9 '18 at 14:47






        • 1




          I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
          – Charlie Harding
          Dec 9 '18 at 19:24












        • @CharlieHarding it was a typo, thanks
          – blue_note
          Dec 9 '18 at 20:54



















        1














        Another option aside from eval is to use the Function constructor. Function is a bit more flexible and allows you to save compiled code instead of having to eval it each time.
        They both carry similar security risks, however.






        var conditional = "";
        for(var i = 1; i <= 6; i++){
        conditional += "document.getElementById('div" + i +"').innerHTML";
        if(i < 6) {
        conditional += " && ";
        }
        }
        const f = new Function('return (' + conditional + ') !== ""');

        console.log(f());

        <div id="div1">1</div>
        <div id="div2"></div>
        <div id="div3">3</div>
        <div id="div4">4</div>
        <div id="div5"></div>
        <div id="div6">6</div>








        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53689001%2fprogrammatically-construct-a-condition-for-use-in-an-if-statement%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          19














          As the other answers said, you can solve your conditions problem more easily.



          But, to answer your new question




          purely from a place of curiosity, is it possible to store and run
          JavaScript expressions or commands in strings?




          Yes, you can write JavaScript code to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.






          share|improve this answer



















          • 1




            Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
            – WillD
            Dec 9 '18 at 4:42
















          19














          As the other answers said, you can solve your conditions problem more easily.



          But, to answer your new question




          purely from a place of curiosity, is it possible to store and run
          JavaScript expressions or commands in strings?




          Yes, you can write JavaScript code to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.






          share|improve this answer



















          • 1




            Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
            – WillD
            Dec 9 '18 at 4:42














          19












          19








          19






          As the other answers said, you can solve your conditions problem more easily.



          But, to answer your new question




          purely from a place of curiosity, is it possible to store and run
          JavaScript expressions or commands in strings?




          Yes, you can write JavaScript code to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.






          share|improve this answer














          As the other answers said, you can solve your conditions problem more easily.



          But, to answer your new question




          purely from a place of curiosity, is it possible to store and run
          JavaScript expressions or commands in strings?




          Yes, you can write JavaScript code to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 9 '18 at 7:59









          Peter Mortensen

          13.5k1983111




          13.5k1983111










          answered Dec 9 '18 at 3:40









          jorbuedo

          596112




          596112








          • 1




            Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
            – WillD
            Dec 9 '18 at 4:42














          • 1




            Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
            – WillD
            Dec 9 '18 at 4:42








          1




          1




          Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
          – WillD
          Dec 9 '18 at 4:42




          Since this most closely answers my question I am going to accept it, though I recognize that for the example I gave there are more direct solutions, and furthermore that eval() has its own problems.
          – WillD
          Dec 9 '18 at 4:42













          25














          You can do the tests in a loop.



          var allOK = true;
          for (var i = 1; i <= 100; i++) {
          if (!document.getElementById("div"+i).innerHTML) {
          allOK = false;
          break;
          }
          }
          if (allOK) {
          console.log("all my divs have content");
          }


          You could also give all your DIVs a common class, then use a built-in iterator.



          var allDivs = document.getElementsByClassName("divClass");
          if (Array.from(allDivs).every(div => div.innerHTML)) {
          console.log("all my divs have content");
          }





          share|improve this answer























          • I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
            – Gaurav
            Dec 9 '18 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 '18 at 3:11










          • +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
            – billynoah
            Dec 9 '18 at 3:27






          • 1




            Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
            – BlueRaja - Danny Pflughoeft
            Dec 9 '18 at 13:43












          • You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
            – Dev
            Dec 10 '18 at 3:52
















          25














          You can do the tests in a loop.



          var allOK = true;
          for (var i = 1; i <= 100; i++) {
          if (!document.getElementById("div"+i).innerHTML) {
          allOK = false;
          break;
          }
          }
          if (allOK) {
          console.log("all my divs have content");
          }


          You could also give all your DIVs a common class, then use a built-in iterator.



          var allDivs = document.getElementsByClassName("divClass");
          if (Array.from(allDivs).every(div => div.innerHTML)) {
          console.log("all my divs have content");
          }





          share|improve this answer























          • I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
            – Gaurav
            Dec 9 '18 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 '18 at 3:11










          • +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
            – billynoah
            Dec 9 '18 at 3:27






          • 1




            Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
            – BlueRaja - Danny Pflughoeft
            Dec 9 '18 at 13:43












          • You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
            – Dev
            Dec 10 '18 at 3:52














          25












          25








          25






          You can do the tests in a loop.



          var allOK = true;
          for (var i = 1; i <= 100; i++) {
          if (!document.getElementById("div"+i).innerHTML) {
          allOK = false;
          break;
          }
          }
          if (allOK) {
          console.log("all my divs have content");
          }


          You could also give all your DIVs a common class, then use a built-in iterator.



          var allDivs = document.getElementsByClassName("divClass");
          if (Array.from(allDivs).every(div => div.innerHTML)) {
          console.log("all my divs have content");
          }





          share|improve this answer














          You can do the tests in a loop.



          var allOK = true;
          for (var i = 1; i <= 100; i++) {
          if (!document.getElementById("div"+i).innerHTML) {
          allOK = false;
          break;
          }
          }
          if (allOK) {
          console.log("all my divs have content");
          }


          You could also give all your DIVs a common class, then use a built-in iterator.



          var allDivs = document.getElementsByClassName("divClass");
          if (Array.from(allDivs).every(div => div.innerHTML)) {
          console.log("all my divs have content");
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 9 '18 at 3:11

























          answered Dec 9 '18 at 3:08









          Barmar

          419k34244344




          419k34244344












          • I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
            – Gaurav
            Dec 9 '18 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 '18 at 3:11










          • +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
            – billynoah
            Dec 9 '18 at 3:27






          • 1




            Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
            – BlueRaja - Danny Pflughoeft
            Dec 9 '18 at 13:43












          • You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
            – Dev
            Dec 10 '18 at 3:52


















          • I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
            – Gaurav
            Dec 9 '18 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 '18 at 3:11










          • +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
            – billynoah
            Dec 9 '18 at 3:27






          • 1




            Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
            – BlueRaja - Danny Pflughoeft
            Dec 9 '18 at 13:43












          • You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
            – Dev
            Dec 10 '18 at 3:52
















          I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
          – Gaurav
          Dec 9 '18 at 3:10




          I suppose document.getElementById("div"+i).innerHTML will return a string not a boolean. isn't it?
          – Gaurav
          Dec 9 '18 at 3:10




          1




          1




          @Gaurav An empty string is falsey.
          – Barmar
          Dec 9 '18 at 3:11




          @Gaurav An empty string is falsey.
          – Barmar
          Dec 9 '18 at 3:11












          +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
          – billynoah
          Dec 9 '18 at 3:27




          +1, slow typing on my part and this is how I would do it. Didn't know about the built in iterator method. very cool!
          – billynoah
          Dec 9 '18 at 3:27




          1




          1




          Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
          – BlueRaja - Danny Pflughoeft
          Dec 9 '18 at 13:43






          Pretty much any time you find yourself breaking out of a loop (especially if the loop just sets a variable), you should pull that out into a function instead. The break becomes a return
          – BlueRaja - Danny Pflughoeft
          Dec 9 '18 at 13:43














          You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
          – Dev
          Dec 10 '18 at 3:52




          You could use [...allDivs] instead of Array.from, although I don't think anything older than ES6 supports it.
          – Dev
          Dec 10 '18 at 3:52











          8














          Why interpret a string of code? There are other means like for loops:



          var conditionResult = true;
          for(var i = 1; conditionResult && (i < 101); i++) {
          conditionResult = conditionResult && document.getElementById('div' + i).innerHTML;
          }

          if(conditionResult) {
          // Do something here
          }


          The for loop condition conditionResult && (i < 101) will break the loop once conditionResult is determined to be falsy; no need to keep looping in this case.



          You can also use array methods like some and every if you have the elements in an array:



          var arr = [/* array of DOM elements */];

          var conditionResult = arr.every(elem => elem.innerHTML); // This is equivalent to (innerHTML && innerHTML && ...)

          var conditionResult = arr.some(elem => elem.innerHTML); // This is equivalent to (innerHTML || innerHTML || ...)





          share|improve this answer




























            8














            Why interpret a string of code? There are other means like for loops:



            var conditionResult = true;
            for(var i = 1; conditionResult && (i < 101); i++) {
            conditionResult = conditionResult && document.getElementById('div' + i).innerHTML;
            }

            if(conditionResult) {
            // Do something here
            }


            The for loop condition conditionResult && (i < 101) will break the loop once conditionResult is determined to be falsy; no need to keep looping in this case.



            You can also use array methods like some and every if you have the elements in an array:



            var arr = [/* array of DOM elements */];

            var conditionResult = arr.every(elem => elem.innerHTML); // This is equivalent to (innerHTML && innerHTML && ...)

            var conditionResult = arr.some(elem => elem.innerHTML); // This is equivalent to (innerHTML || innerHTML || ...)





            share|improve this answer


























              8












              8








              8






              Why interpret a string of code? There are other means like for loops:



              var conditionResult = true;
              for(var i = 1; conditionResult && (i < 101); i++) {
              conditionResult = conditionResult && document.getElementById('div' + i).innerHTML;
              }

              if(conditionResult) {
              // Do something here
              }


              The for loop condition conditionResult && (i < 101) will break the loop once conditionResult is determined to be falsy; no need to keep looping in this case.



              You can also use array methods like some and every if you have the elements in an array:



              var arr = [/* array of DOM elements */];

              var conditionResult = arr.every(elem => elem.innerHTML); // This is equivalent to (innerHTML && innerHTML && ...)

              var conditionResult = arr.some(elem => elem.innerHTML); // This is equivalent to (innerHTML || innerHTML || ...)





              share|improve this answer














              Why interpret a string of code? There are other means like for loops:



              var conditionResult = true;
              for(var i = 1; conditionResult && (i < 101); i++) {
              conditionResult = conditionResult && document.getElementById('div' + i).innerHTML;
              }

              if(conditionResult) {
              // Do something here
              }


              The for loop condition conditionResult && (i < 101) will break the loop once conditionResult is determined to be falsy; no need to keep looping in this case.



              You can also use array methods like some and every if you have the elements in an array:



              var arr = [/* array of DOM elements */];

              var conditionResult = arr.every(elem => elem.innerHTML); // This is equivalent to (innerHTML && innerHTML && ...)

              var conditionResult = arr.some(elem => elem.innerHTML); // This is equivalent to (innerHTML || innerHTML || ...)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 9 '18 at 15:48

























              answered Dec 9 '18 at 3:07









              ibrahim mahrir

              21.7k41846




              21.7k41846























                  2














                  You can set condition to true and check each one, setting condition to false and break out of the loop if any are false.



                  var conditional = true;
                  for(var i = 1; i <= 100; i++){
                  if (!document.getElementById('div' + i).innerHTML) {
                  condition = false;
                  break;
                  }
                  }





                  share|improve this answer


























                    2














                    You can set condition to true and check each one, setting condition to false and break out of the loop if any are false.



                    var conditional = true;
                    for(var i = 1; i <= 100; i++){
                    if (!document.getElementById('div' + i).innerHTML) {
                    condition = false;
                    break;
                    }
                    }





                    share|improve this answer
























                      2












                      2








                      2






                      You can set condition to true and check each one, setting condition to false and break out of the loop if any are false.



                      var conditional = true;
                      for(var i = 1; i <= 100; i++){
                      if (!document.getElementById('div' + i).innerHTML) {
                      condition = false;
                      break;
                      }
                      }





                      share|improve this answer












                      You can set condition to true and check each one, setting condition to false and break out of the loop if any are false.



                      var conditional = true;
                      for(var i = 1; i <= 100; i++){
                      if (!document.getElementById('div' + i).innerHTML) {
                      condition = false;
                      break;
                      }
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 9 '18 at 3:10









                      billynoah

                      10.5k54261




                      10.5k54261























                          2














                          Use document.querySelectorAll for this type of operation






                          // Get all the divs that have ids which start with div
                          var theDivs = document.querySelectorAll('[id^="div"]');
                          var i,l,el,divsWithContent = ;

                          // Loop through all theDivs
                          l = theDivs.length;
                          for(i = 0; i < l; i++) {
                          // el is the div
                          el = theDivs[i];

                          // Test to make sure the id is div followed by one or more digits
                          if (/^divd+$/.test(el.id)) {
                          // If the div has something in it other than spaces, it's got content
                          if (el.textContent.trim() !== "") {
                          // Save the divs with content in the array
                          divsWithContent.push(el.id);
                          }
                          }
                          }

                          // Show the results
                          document.getElementById("result").textContent = divsWithContent.join("n");

                          <h1>Div test</h1>
                          <div id="div1">This</div>
                          <div id="div2">that</div>
                          <div id="div3"></div>
                          <div id="div4">and</div>
                          <div id="div5">the other thing</div>
                          <h2>Divs with content</h2>
                          <pre id="result"></pre>





                          Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll






                          share|improve this answer


























                            2














                            Use document.querySelectorAll for this type of operation






                            // Get all the divs that have ids which start with div
                            var theDivs = document.querySelectorAll('[id^="div"]');
                            var i,l,el,divsWithContent = ;

                            // Loop through all theDivs
                            l = theDivs.length;
                            for(i = 0; i < l; i++) {
                            // el is the div
                            el = theDivs[i];

                            // Test to make sure the id is div followed by one or more digits
                            if (/^divd+$/.test(el.id)) {
                            // If the div has something in it other than spaces, it's got content
                            if (el.textContent.trim() !== "") {
                            // Save the divs with content in the array
                            divsWithContent.push(el.id);
                            }
                            }
                            }

                            // Show the results
                            document.getElementById("result").textContent = divsWithContent.join("n");

                            <h1>Div test</h1>
                            <div id="div1">This</div>
                            <div id="div2">that</div>
                            <div id="div3"></div>
                            <div id="div4">and</div>
                            <div id="div5">the other thing</div>
                            <h2>Divs with content</h2>
                            <pre id="result"></pre>





                            Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll






                            share|improve this answer
























                              2












                              2








                              2






                              Use document.querySelectorAll for this type of operation






                              // Get all the divs that have ids which start with div
                              var theDivs = document.querySelectorAll('[id^="div"]');
                              var i,l,el,divsWithContent = ;

                              // Loop through all theDivs
                              l = theDivs.length;
                              for(i = 0; i < l; i++) {
                              // el is the div
                              el = theDivs[i];

                              // Test to make sure the id is div followed by one or more digits
                              if (/^divd+$/.test(el.id)) {
                              // If the div has something in it other than spaces, it's got content
                              if (el.textContent.trim() !== "") {
                              // Save the divs with content in the array
                              divsWithContent.push(el.id);
                              }
                              }
                              }

                              // Show the results
                              document.getElementById("result").textContent = divsWithContent.join("n");

                              <h1>Div test</h1>
                              <div id="div1">This</div>
                              <div id="div2">that</div>
                              <div id="div3"></div>
                              <div id="div4">and</div>
                              <div id="div5">the other thing</div>
                              <h2>Divs with content</h2>
                              <pre id="result"></pre>





                              Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll






                              share|improve this answer












                              Use document.querySelectorAll for this type of operation






                              // Get all the divs that have ids which start with div
                              var theDivs = document.querySelectorAll('[id^="div"]');
                              var i,l,el,divsWithContent = ;

                              // Loop through all theDivs
                              l = theDivs.length;
                              for(i = 0; i < l; i++) {
                              // el is the div
                              el = theDivs[i];

                              // Test to make sure the id is div followed by one or more digits
                              if (/^divd+$/.test(el.id)) {
                              // If the div has something in it other than spaces, it's got content
                              if (el.textContent.trim() !== "") {
                              // Save the divs with content in the array
                              divsWithContent.push(el.id);
                              }
                              }
                              }

                              // Show the results
                              document.getElementById("result").textContent = divsWithContent.join("n");

                              <h1>Div test</h1>
                              <div id="div1">This</div>
                              <div id="div2">that</div>
                              <div id="div3"></div>
                              <div id="div4">and</div>
                              <div id="div5">the other thing</div>
                              <h2>Divs with content</h2>
                              <pre id="result"></pre>





                              Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll






                              // Get all the divs that have ids which start with div
                              var theDivs = document.querySelectorAll('[id^="div"]');
                              var i,l,el,divsWithContent = ;

                              // Loop through all theDivs
                              l = theDivs.length;
                              for(i = 0; i < l; i++) {
                              // el is the div
                              el = theDivs[i];

                              // Test to make sure the id is div followed by one or more digits
                              if (/^divd+$/.test(el.id)) {
                              // If the div has something in it other than spaces, it's got content
                              if (el.textContent.trim() !== "") {
                              // Save the divs with content in the array
                              divsWithContent.push(el.id);
                              }
                              }
                              }

                              // Show the results
                              document.getElementById("result").textContent = divsWithContent.join("n");

                              <h1>Div test</h1>
                              <div id="div1">This</div>
                              <div id="div2">that</div>
                              <div id="div3"></div>
                              <div id="div4">and</div>
                              <div id="div5">the other thing</div>
                              <h2>Divs with content</h2>
                              <pre id="result"></pre>





                              // Get all the divs that have ids which start with div
                              var theDivs = document.querySelectorAll('[id^="div"]');
                              var i,l,el,divsWithContent = ;

                              // Loop through all theDivs
                              l = theDivs.length;
                              for(i = 0; i < l; i++) {
                              // el is the div
                              el = theDivs[i];

                              // Test to make sure the id is div followed by one or more digits
                              if (/^divd+$/.test(el.id)) {
                              // If the div has something in it other than spaces, it's got content
                              if (el.textContent.trim() !== "") {
                              // Save the divs with content in the array
                              divsWithContent.push(el.id);
                              }
                              }
                              }

                              // Show the results
                              document.getElementById("result").textContent = divsWithContent.join("n");

                              <h1>Div test</h1>
                              <div id="div1">This</div>
                              <div id="div2">that</div>
                              <div id="div3"></div>
                              <div id="div4">and</div>
                              <div id="div5">the other thing</div>
                              <h2>Divs with content</h2>
                              <pre id="result"></pre>






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 9 '18 at 3:46









                              user2182349

                              7,10811633




                              7,10811633























                                  1














                                  You could just store the document.getElementById('divXX').innerHTML items in an array, and then, just use



                                  items.reduce((a, b) => a && b);


                                  That way, you can change individual div elements in your expression without having to re-created the whole list






                                  share|improve this answer



















                                  • 2




                                    It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                    – Jörg W Mittag
                                    Dec 9 '18 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 '18 at 14:47






                                  • 1




                                    I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                    – Charlie Harding
                                    Dec 9 '18 at 19:24












                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 '18 at 20:54
















                                  1














                                  You could just store the document.getElementById('divXX').innerHTML items in an array, and then, just use



                                  items.reduce((a, b) => a && b);


                                  That way, you can change individual div elements in your expression without having to re-created the whole list






                                  share|improve this answer



















                                  • 2




                                    It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                    – Jörg W Mittag
                                    Dec 9 '18 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 '18 at 14:47






                                  • 1




                                    I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                    – Charlie Harding
                                    Dec 9 '18 at 19:24












                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 '18 at 20:54














                                  1












                                  1








                                  1






                                  You could just store the document.getElementById('divXX').innerHTML items in an array, and then, just use



                                  items.reduce((a, b) => a && b);


                                  That way, you can change individual div elements in your expression without having to re-created the whole list






                                  share|improve this answer














                                  You could just store the document.getElementById('divXX').innerHTML items in an array, and then, just use



                                  items.reduce((a, b) => a && b);


                                  That way, you can change individual div elements in your expression without having to re-created the whole list







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Dec 9 '18 at 20:52

























                                  answered Dec 9 '18 at 11:21









                                  blue_note

                                  11k31832




                                  11k31832








                                  • 2




                                    It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                    – Jörg W Mittag
                                    Dec 9 '18 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 '18 at 14:47






                                  • 1




                                    I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                    – Charlie Harding
                                    Dec 9 '18 at 19:24












                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 '18 at 20:54














                                  • 2




                                    It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                    – Jörg W Mittag
                                    Dec 9 '18 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 '18 at 14:47






                                  • 1




                                    I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                    – Charlie Harding
                                    Dec 9 '18 at 19:24












                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 '18 at 20:54








                                  2




                                  2




                                  It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                  – Jörg W Mittag
                                  Dec 9 '18 at 14:14




                                  It's annoying that operators are not functions, otherwise this would be very nicely expressed as items.reduce(&).
                                  – Jörg W Mittag
                                  Dec 9 '18 at 14:14












                                  @JörgWMittag: it would. but I've seen few languages where you can write this
                                  – blue_note
                                  Dec 9 '18 at 14:47




                                  @JörgWMittag: it would. but I've seen few languages where you can write this
                                  – blue_note
                                  Dec 9 '18 at 14:47




                                  1




                                  1




                                  I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                  – Charlie Harding
                                  Dec 9 '18 at 19:24






                                  I think you need to use && rather than &: .innerHTML is a string, but & performs bitwise AND on the bits of numbers, so the string is converted to a number. However, in this case, .reduce((a, b) => a && b) is the same as .every(a => a), or even more simply, ['div1','div2', /*...*/ 'div100'].every(div => document.getElementById(div).innerHTML)
                                  – Charlie Harding
                                  Dec 9 '18 at 19:24














                                  @CharlieHarding it was a typo, thanks
                                  – blue_note
                                  Dec 9 '18 at 20:54




                                  @CharlieHarding it was a typo, thanks
                                  – blue_note
                                  Dec 9 '18 at 20:54











                                  1














                                  Another option aside from eval is to use the Function constructor. Function is a bit more flexible and allows you to save compiled code instead of having to eval it each time.
                                  They both carry similar security risks, however.






                                  var conditional = "";
                                  for(var i = 1; i <= 6; i++){
                                  conditional += "document.getElementById('div" + i +"').innerHTML";
                                  if(i < 6) {
                                  conditional += " && ";
                                  }
                                  }
                                  const f = new Function('return (' + conditional + ') !== ""');

                                  console.log(f());

                                  <div id="div1">1</div>
                                  <div id="div2"></div>
                                  <div id="div3">3</div>
                                  <div id="div4">4</div>
                                  <div id="div5"></div>
                                  <div id="div6">6</div>








                                  share|improve this answer


























                                    1














                                    Another option aside from eval is to use the Function constructor. Function is a bit more flexible and allows you to save compiled code instead of having to eval it each time.
                                    They both carry similar security risks, however.






                                    var conditional = "";
                                    for(var i = 1; i <= 6; i++){
                                    conditional += "document.getElementById('div" + i +"').innerHTML";
                                    if(i < 6) {
                                    conditional += " && ";
                                    }
                                    }
                                    const f = new Function('return (' + conditional + ') !== ""');

                                    console.log(f());

                                    <div id="div1">1</div>
                                    <div id="div2"></div>
                                    <div id="div3">3</div>
                                    <div id="div4">4</div>
                                    <div id="div5"></div>
                                    <div id="div6">6</div>








                                    share|improve this answer
























                                      1












                                      1








                                      1






                                      Another option aside from eval is to use the Function constructor. Function is a bit more flexible and allows you to save compiled code instead of having to eval it each time.
                                      They both carry similar security risks, however.






                                      var conditional = "";
                                      for(var i = 1; i <= 6; i++){
                                      conditional += "document.getElementById('div" + i +"').innerHTML";
                                      if(i < 6) {
                                      conditional += " && ";
                                      }
                                      }
                                      const f = new Function('return (' + conditional + ') !== ""');

                                      console.log(f());

                                      <div id="div1">1</div>
                                      <div id="div2"></div>
                                      <div id="div3">3</div>
                                      <div id="div4">4</div>
                                      <div id="div5"></div>
                                      <div id="div6">6</div>








                                      share|improve this answer












                                      Another option aside from eval is to use the Function constructor. Function is a bit more flexible and allows you to save compiled code instead of having to eval it each time.
                                      They both carry similar security risks, however.






                                      var conditional = "";
                                      for(var i = 1; i <= 6; i++){
                                      conditional += "document.getElementById('div" + i +"').innerHTML";
                                      if(i < 6) {
                                      conditional += " && ";
                                      }
                                      }
                                      const f = new Function('return (' + conditional + ') !== ""');

                                      console.log(f());

                                      <div id="div1">1</div>
                                      <div id="div2"></div>
                                      <div id="div3">3</div>
                                      <div id="div4">4</div>
                                      <div id="div5"></div>
                                      <div id="div6">6</div>








                                      var conditional = "";
                                      for(var i = 1; i <= 6; i++){
                                      conditional += "document.getElementById('div" + i +"').innerHTML";
                                      if(i < 6) {
                                      conditional += " && ";
                                      }
                                      }
                                      const f = new Function('return (' + conditional + ') !== ""');

                                      console.log(f());

                                      <div id="div1">1</div>
                                      <div id="div2"></div>
                                      <div id="div3">3</div>
                                      <div id="div4">4</div>
                                      <div id="div5"></div>
                                      <div id="div6">6</div>





                                      var conditional = "";
                                      for(var i = 1; i <= 6; i++){
                                      conditional += "document.getElementById('div" + i +"').innerHTML";
                                      if(i < 6) {
                                      conditional += " && ";
                                      }
                                      }
                                      const f = new Function('return (' + conditional + ') !== ""');

                                      console.log(f());

                                      <div id="div1">1</div>
                                      <div id="div2"></div>
                                      <div id="div3">3</div>
                                      <div id="div4">4</div>
                                      <div id="div5"></div>
                                      <div id="div6">6</div>






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Dec 10 '18 at 0:45









                                      S. Foster

                                      464




                                      464






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53689001%2fprogrammatically-construct-a-condition-for-use-in-an-if-statement%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Plaza Victoria

                                          Puebla de Zaragoza

                                          Musa