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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
27
down vote

favorite












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 at 3:38











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






  • 1




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














up vote
27
down vote

favorite












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 at 3:38











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






  • 1




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












up vote
27
down vote

favorite









up vote
27
down vote

favorite











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 at 7:57









Peter Mortensen

13.4k1983111




13.4k1983111










asked Dec 9 at 3:03









WillD

397113




397113







  • 5




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











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






  • 1




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












  • 5




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











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






  • 1




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







5




5




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





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













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




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




1




1




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




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












7 Answers
7






active

oldest

votes

















up vote
16
down vote



accepted










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






















  • 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 at 4:42

















up vote
23
down vote













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 at 3:10






  • 1




    @Gaurav An empty string is falsey.
    – Barmar
    Dec 9 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 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 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 at 3:52

















up vote
8
down vote













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





























    up vote
    2
    down vote













    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



























      up vote
      2
      down vote













      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



























        up vote
        1
        down vote













        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 at 14:14










        • @JörgWMittag: it would. but I've seen few languages where you can write this
          – blue_note
          Dec 9 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 at 19:24











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

















        up vote
        1
        down vote













        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








          up vote
          16
          down vote



          accepted










          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






















          • 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 at 4:42














          up vote
          16
          down vote



          accepted










          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






















          • 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 at 4:42












          up vote
          16
          down vote



          accepted







          up vote
          16
          down vote



          accepted






          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 at 7:59









          Peter Mortensen

          13.4k1983111




          13.4k1983111










          answered Dec 9 at 3:40









          jorbuedo

          55612




          55612











          • 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 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 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 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 at 4:42












          up vote
          23
          down vote













          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 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 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 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 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 at 3:52














          up vote
          23
          down vote













          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 at 3:10






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 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 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 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 at 3:52












          up vote
          23
          down vote










          up vote
          23
          down vote









          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 at 3:11

























          answered Dec 9 at 3:08









          Barmar

          417k34240341




          417k34240341











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






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 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 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 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 at 3:52
















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






          • 1




            @Gaurav An empty string is falsey.
            – Barmar
            Dec 9 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 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 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 at 3:52















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




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




          1




          1




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




          @Gaurav An empty string is falsey.
          – Barmar
          Dec 9 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 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 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 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 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 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 at 3:52










          up vote
          8
          down vote













          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


























            up vote
            8
            down vote













            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
























              up vote
              8
              down vote










              up vote
              8
              down vote









              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 at 15:48

























              answered Dec 9 at 3:07









              ibrahim mahrir

              21.7k41846




              21.7k41846




















                  up vote
                  2
                  down vote













                  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
























                    up vote
                    2
                    down vote













                    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






















                      up vote
                      2
                      down vote










                      up vote
                      2
                      down vote









                      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 at 3:10









                      billynoah

                      10.3k54261




                      10.3k54261




















                          up vote
                          2
                          down vote













                          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
























                            up vote
                            2
                            down vote













                            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






















                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              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 at 3:46









                              user2182349

                              7,10811633




                              7,10811633




















                                  up vote
                                  1
                                  down vote













                                  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 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 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 at 19:24











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














                                  up vote
                                  1
                                  down vote













                                  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 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 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 at 19:24











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












                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  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 at 20:52

























                                  answered Dec 9 at 11:21









                                  blue_note

                                  10.9k31831




                                  10.9k31831







                                  • 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 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 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 at 19:24











                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 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 at 14:14










                                  • @JörgWMittag: it would. but I've seen few languages where you can write this
                                    – blue_note
                                    Dec 9 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 at 19:24











                                  • @CharlieHarding it was a typo, thanks
                                    – blue_note
                                    Dec 9 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 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 at 14:14












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




                                  @JörgWMittag: it would. but I've seen few languages where you can write this
                                  – blue_note
                                  Dec 9 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 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 at 19:24













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




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










                                  up vote
                                  1
                                  down vote













                                  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
























                                    up vote
                                    1
                                    down vote













                                    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






















                                      up vote
                                      1
                                      down vote










                                      up vote
                                      1
                                      down vote









                                      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 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

                                          How to check contact read email or not when send email to Individual?

                                          Displaying single band from multi-band raster using QGIS

                                          How many registers does an x86_64 CPU actually have?