1

I have a simple function in javascript that hides all css divs on page load:

function hideAllDivs() {
    var a5 = jQuery('.a5'),
        a2 = jQuery('.a2'),
        b2 = jQuery('.b2'),
        hd3 = jQuery('.hd3'),
        hd6 = jQuery('.hd6');

    a5.hide();
    a2.hide();
    b2.hide();
    hd3.hide();
    hd6.hide();
}

As you can see I have to go through each one by one to hide them. Is there a way to store these into an array and just iterate through them all at once? That way if I add a new var chained query, I don't have to then go further down the function and manually hide it?

Any help would be greatly appreciated.

2
  • 1
    try var tt = ['.a5','.a2'...]; for(var i=0,j=tt.length;i<j;i++){ $(tt[i]).hide() } Commented Nov 15, 2017 at 12:24
  • Possible Duplicate: stackoverflow.com/questions/10515888/…. You can also refer to Docs Commented Nov 15, 2017 at 12:26

2 Answers 2

2

You could give them a common class and then hide using this class as a selector that combine all those targeted elements for this operation, e.g :

function hideAllDivs() {
    jQuery('.common_class').hide();
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2

You can just use a single selector:

jQuery('.a5, .a2, .b2, .hd3, .hd6').hide();

Alternatively, you might want to consider creating a new class that you apply to elements you want to hide, and just hide that single class - depends on your overall structure, but that way you don't need to come back and edit this function ever again, just apply that class where needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.