1
document.getElementById("myId").style.left = 100px;

Is there a SHORT way to use the code above to a class?

Will the code below work?

doucment.getElementsByClassName("myClass").style.left = 100px;

What I wanted to do was to move multiple images to the same place and it should be flexible so that it would work if the user wanted 1, 2, 3 or more images to move to that place.

aidz927
  • 35
  • 4

2 Answers2

3

The getElementsByClassName() function returns a NodeList, so you'll need to iterate over it and apply the style to each element in turn. That's relatively easy to do using forEach, but you need to convert to an Array first:

Array.prototype.slice.call(document.getElementsByClassName("myClass")).forEach(function(elem,index) {
    elem.style.left = 100px;
});
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • 2
    forEach is not a method of nodeList object, you have to convert it into array. Array.prototype.slice.call(document.getElementsByClassName("myClass")).forEach – Arnaud Gueras Nov 04 '15 at 14:00
  • wait wait I'm lost here so where does the Array.prototype.slice....... come in the code above? – aidz927 Nov 04 '15 at 14:12
  • @GuerasArnaud You're right, thanks for pointing that out. I think I was thinking of Dojo when writing the answer. – Anthony Grist Nov 04 '15 at 15:48
2

Yes, but getElementsByClassName returns an array-like object (an HTMLCollection), so you need to specify the element(s) you want to apply the change to. For example:

document.getElementsByClassName("myClass")[0].style.left = 100px;

Would be applied to the first element with that class. Otherwise you need to loop over the set.

j08691
  • 204,283
  • 31
  • 260
  • 272