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

  • A+

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)


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 to a string and execute it later with eval. Which you should not do if you are concerned with security or performance.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: