2

In the site I'm currently building, I have found the repeated need to set style attributes for each member of an array of elements.

Of course, to do this, I have to make a loop that iterates through all of the members of the array, like so:

for (var i = 0; i < ElementArray.length; i++) {
    ElementArray[i].style.display = "none";
}

In the spirit of DRY, I'm trying to write a function that can do this for me each time I need it... something like this:

function applyToArray(ElementArray, attr, val) {
    for (var i = 0; i < ElementArray.length; i++) {
        ElementArray[i].style.attr = val;
    }
}

Of course, I can't imagine that this would ever work, but I can't seem to find a way to embed a variable into the property assignment statement.

(Forgive me, I've only been using JS for a few months now, so I have yet to completely understand the design of the language. If it's impossible, could you please point me to the correct way of doing what I'm trying to achieve?)

forresthopkinsa
  • 1,339
  • 1
  • 24
  • 29
  • Thanks Moderators for linking the other post! I was searching this site for an hour without finding results -- seems I was looking up the wrong terms! – forresthopkinsa Apr 19 '16 at 20:31

0 Answers0