ahdrum87
ahdrum87

Reputation: 45

For Loop to Programmatically hide elements

I am currently trying to programmatically hide div elements on a page using an Array and loop in jQuery, but it doesn't seem to work.

I have done alerts and console.log to confirm the array is firing and the loop is working through the items, but it's the .hide() method that seems to be giving issue. Any help would be appreciated.

Thanks

$(document).ready(function(){
       var divsToHide = ["fin_0", "fin_1", "fin_2", "fin_3", "fin_4", "fin_5", 
"fin_6", "fin_7", "fin_8", "fin_9", "fin_10", "fin_10-1", "fin_10-2", "fin_10-3", 
"fin_10-4", "fin_10-5", "fin_10-6", "fin_10-7", "fin_10-8", "fin_10-9", "fin_20", 
"fin_21", "fin_22", "fin_23"];

    $.each(divsToHide, function(index, value)
    {
        var currentDiv = "div#" + value;
        var stringCurrent = currentDiv.toString();
        var currentHide = $(' stringCurrent ');

            console.log(currentDiv);
            currentHide.hide();
    }); 
});

Upvotes: 1

Views: 133

Answers (3)

BlueSam
BlueSam

Reputation: 1888

Even better, you should use

 $.each(divsToHide, function(index, value)
 {
    $("#" + value).hide()
 }); 

since an element id should be unique to the document

Upvotes: 5

Koogle
Koogle

Reputation: 471

You need to remove the ' around stringCurrent. Otherwise your string is not interpreted but jquery searches for ' stringCurrent '

Upvotes: 2

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13174

You should probably use:

var currentHide = $(stringCurrent);

Your code

var currentHide = $(' stringCurrent ');

has no reference to stringCurrent variable, it just try to find <stringCurrent> element.

Upvotes: 7

Related Questions