HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Loop through string array with exit if test passed

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraywithlooppassedexittestthroughstring

Problem

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 && 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 > 0;


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

var valid = false;
var content = $('.TestModule');
if (content !== null && typeof (content) !== "undefined") {
    var elementTypes = ['btn', 'textbox', 'ui-jqgrid', 'flexboxdiv', 'headerlabel'];
    for (i = 0; i  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.

Solution

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


is equivalent to

return $('.TestModule').first().find('.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel').length > 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(', ');

Code Snippets

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

return $('.TestModule').first().find(selector).length > 0;
return $('.TestModule').first().find(selector).length > 0;
return $('.TestModule').first().find('.btn, .textbox, .ui-jqgrid, .flexboxdiv, .headerlabel').length > 0;
var elementTypes = ['.btn', '.textbox', '.ui-jqgrid', '.flexboxdiv', '.headerlabel', '#myId', 'input', 'input[name="firstname"]'];
var selector = elementTypes.join(', ');

Context

StackExchange Code Review Q#111700, answer score: 5

Revisions (0)

No revisions yet.