Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shorthand way to duplicate strings

I have this code in a function, and want to shorten it - it applies the same style to every item in an array.

document.getElementById(divsArray[0]).style.visibility = 'hidden';
document.getElementById(divsArray[1]).style.visibility = 'hidden';
document.getElementById(divsArray[2]).style.visibility = 'hidden';
document.getElementById(divsArray[3]).style.visibility = 'hidden';

NO answer to date worked (Because I am looping thru the code??)

Resolved it by setting only the previously displayed slide visibility to hidden

x = i;
i = i+1;

document.getElementById(divsArray[x]).style.visibility = 'hidden';
like image 982
Rhys Avatar asked Aug 18 '10 15:08

Rhys


3 Answers

How about using a loop:

for (var i = 0; i < 4; i++) {
    document.getElementById(divsArray[i]).style.visibility = 'hidden'; 
}
like image 180
Darin Dimitrov Avatar answered Nov 19 '22 23:11

Darin Dimitrov


Just to provide something different, a jQuery solution:

$(divsArray).each(function() {
  $(this).css("visibility", "hidden");
});

Edit: It looks like you might have to collect your DOM references first. (divsArray is really just an array of div names, and not the divs themselves?)

$(divsArray).each(function() {
  $("#" + this).css({ "visibility": "hidden" });
});
like image 44
sworoc Avatar answered Nov 20 '22 00:11

sworoc


It sounds to me that there might be more divs... Might I suggest this change to Darin's code:

for (var i = 0; i < divsArray.length; i++) {
   document.getElementById(divsArray[i]).style.visibility = 'hidden'; 
}
like image 4
It Grunt Avatar answered Nov 19 '22 23:11

It Grunt