Javascript shorthand way to duplicate strings
Asked Answered
T

9

7

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';
Trinh answered 18/8, 2010 at 15:6 Comment(15)
Holy down votes, Batman!Chowchow
all are copying the same answer on this questionDestructor
@Amr: whether they're copying or not is unclear (it's an obvious answer, so probably not) but they don't add anything either and so should have been deleted.Krever
Each answer is slightly different. I don't think they're copying -- but it's a logical answer to put it in a for loop of some sort. Plus, each answer is within seconds of each other. That doesn't look like copying to me -- looks like everyone had the same suggestion.Chowchow
@Shog9: But Rhys hasn't selected an answer. Why should they delete an answer when the questioner hasn't selected an answer?Chowchow
@DHoerster: why would you knowingly leave a duplicate answer around? Either edit to distinguish it in some way (as did sje397, sworoc) or remove it. Otherwise, it serves no purpose!Krever
@Shog9: who died and made you the boss?Descendible
@rmeador: are you absolving yourself of responsibility?Krever
@Shog9: This site is the free market at work -- everyone wants their answer to be selected. So let's say that you and I both answered this question, and I used for(var i=0;i<4;i++) and you used for(i=0;i<4;i++). The answers are essentially the same, but slightly different. If I answered 4 seconds ahead of you, would you delete your answer, even though you know you're more right than me? That's why no one deleted their answers -- they're all slightly different, and they're leaving it up to Rhys to decide.Chowchow
@Rhys: You didn't think your question would generate this kind of interaction, eh? This is great! :)Chowchow
@DHoerster: Actually, yes - when I post an answer that doesn't add anything to what's already been posted, I'll either remove it or work to add something extra to it (in your example, I could hypothetically add an explicit declaration for i and go on to explain that I prefer this style because for(var... can be misleading to readers familiar with other languages where for introduces scope - but to leave the answer stand, assuming that a reader unfamiliar with looping will somehow know my reasoning, does more harm than good). And re: the free market: I'm participating in that market...Krever
BTW: rather than dragging the discussion here too far off-topic, consider contributing to this question on Meta: What’s the appropriate etiquette when two people correctly answer a question at the same time?Krever
Gosh - what a turmoil! I'm in a different time zone and came back to find all this. I tried all the solutions, and they all freeze the function, or display only divsArray[0] Should I post the entire code? Seems there must be some element in it that is creating a block.Trinh
@Rhys: at this point, if you're still encountering problems you might want to open a new question and post enough of the code to reproduce what you're seeing.Krever
@Shog9'- Thanks I eventually solved it myself by setting a value for divsArray[x] that hid the previous slide in the loop, instead of repeatedly setting every element in the array to 'hidden'Trinh
G
8

How about using a loop:

for (var i = 0; i < 4; i++) {
    document.getElementById(divsArray[i]).style.visibility = 'hidden'; 
}
Grendel answered 18/8, 2010 at 15:7 Comment(1)
Any reason for the downvote? Please leave a comment when downvoting an answer.Grendel
P
5

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" });
});
Perspicuity answered 18/8, 2010 at 15:15 Comment(5)
Dude, you're asking for trouble with that answer. This is a tough crowd! :) Check out the comments. :)Chowchow
@D Hoerster - ha ha, your not wrong I was just about to add a comment and the anwswer was deleted part way through! :)Selfconfidence
if divsArray is all id strings, it should be $('#'+this).css("visibility", "hidden"); right?Mainstream
Yes, I added how I would do it to my answer for clarity.Perspicuity
I like this code because it is really short, and because it offers the possibility of varying the number of items in the arrayTrinh
A
4

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'; 
}
Acis answered 18/8, 2010 at 15:31 Comment(3)
I like this on principle, though strictly-speaking it isn't necessarily a replacement for what the OP wrote.Krever
I wouldn't use divsArray.length unless the OP explicitly says that he wants to use all the elements in the array. What if he wants only the first four elements? But it's a good point anyway.Grendel
@Darin OP does state every item in the array.Mainstream
D
4

And here's how it works in both Prototype and Mootools:

$(divsArray).each(function(item) {
  $(item).setStyle({visibility: "hidden"});
});
Deckhouse answered 18/8, 2010 at 15:45 Comment(0)
C
4

You can put the following function in the same/descendant scope of divsArray.

function baka(idx) {
  document.getElementById(divsArray[idx]).style.visibility = 'hidden';
}

Then you can do either

baka(0);
baka(1);
baka(2);
baka(3);

or

for (var i = 0; i < 4; i++)
  baka(i);

It looks pointless, but if you have more arrays like that, you may want to modify your function like this:

function aho(arr, idx) {
  document.getElementById(arr[idx]).style.visibility = 'hidden';
}

and loop through any array like this:

for (var i = 0; i < divsArray.length; i++)
  aho(divsArray, i);

And no, there are no macros nor are there templates.

Coe answered 18/8, 2010 at 15:56 Comment(1)
Very creative, +1 for providing an interesting answer.Perspicuity
G
2
for (i=0;i<4;i++) {
  document.getElementById(divsArray[i]).style.visibility='hidden';
}
Glomeration answered 18/8, 2010 at 15:7 Comment(2)
It's good style to declare your index variable somewhere (though not necessarily in the for() statement, since that doesn't create scope anyway) to avoid problems with globals. But Darin beat you to the punch this time... ;-)Krever
"Beaten to the punch" by all of 4 seconds (according to what I saw when the page reloaded. I didn't bother with deleting as I figured it reinforced the point that it was the way to do it.Glomeration
M
1

as long as we're all piling on, i'll take the most direct approach :D

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

and just to go against the grain:

var d = null, i = 0;
while (d = document.getElementById(divsArray[i++])) {
    d.style.visibility = 'hidden';
}
Mainstream answered 18/8, 2010 at 17:6 Comment(0)
H
1

I couldn't "resist" to the challenge. I would say you add them the same class and do something like (Prototype example):

$$('.className').invoke('setStyle', { 'visibility' : 'hidden' });
Haeres answered 18/8, 2010 at 19:43 Comment(1)
+1 for invoke, didn't think of that, but apart from that you are making assumptions (maybe there is not a common css class or maybe there is and it's also used by other components). So you must find a way to convert an array of ids to a map of elements first. My guess would be arrayOfIds.map($).invoke() but I am not sure.Deckhouse
A
0

We can iterate over array containing ids using Array.prototype.forEach() and ES6's Arrow Functions:

var elemIds = ['two', 'four', 'six'];

elemIds.forEach(id => {document.getElementById(id).style.visibility = 'hidden';});
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<div id="four">Four</div>
<div id="five">Five</div>
<div id="six">Six</div>
<div id="seven">Seven</div>
Asiaasian answered 15/11, 2017 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.