Loop through string array with exit if test passed I need to return True if a page contains any of a list of element types. This code works.

var elements = 0;
var content = $('.TestModule');
if (content !== null &amp;&amp; typeof (content) !== "undefined") {
    elements += content.first().find('.btn').length;
    elements += content.first().find('.textbox').length;
    elements += content.first().find('.ui-jqgrid').length;
    elements += content.first().find('.flexboxdiv').length;
    elements += content.first().find('.headerlabel').length;
}
return elements &gt; 0;


But always runs every test which is obviously inefficient so I changed to;

var valid = false;
var content = $('.TestModule');
if (content !== null &amp;&amp; typeof (content) !== "undefined") {
    var elementTypes = ['btn', 'textbox', 'ui-jqgrid', 'flexboxdiv', 'headerlabel'];
    for (i = 0; i &lt; elementTypes.length; i++) {
        var num = content.first().find('.' + elementTypes[i]).length;
        if (num &gt; 0) {
            valid = true;
            break;
        }
    }
}
return valid;


Which also works and runs the minimum number of tests. But it looks pretty clunky to me. Can you suggest a better loop/structure/test, please? I don't need a count of element types, just to know whether one or more of any type exists.
Join the string to create a jQuery selector

var elementTypes = ['btn', 'textbox', 'ui-jqgrid', 'flexboxdiv', 'headerlabel'];
var selector = '.' + elementTypes.join(', .');

return $('.TestModule').first().find(selector).length &gt; 0;


The variable selector will return the string '.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel' which can be used in the jQuery selector.

The statement

return $('.TestModule').first().find(selector).length &gt; 0;


is equivalent to 

return $('.TestModule').first().find('.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel').length &gt; 0;


after the string substitution.



To make it more dynamic, store complete selector in the array and join the array by ,-comma.

var elementTypes = ['.btn', '.textbox', '.ui-jqgrid', '.flexboxdiv', '.headerlabel', '#myId', 'input', 'input[name="firstname"]'];
var selector = elementTypes.join(', ');