3
  <script type="text/ecmascript">
  <![CDATA[
  function setCoordinates(circle) {
  var centerX = Math.round(Math.random() * 1000);
  var centerY = Math.round(Math.random() * 1000);      
  circle.setAttribute("cx",centerX);
  circle.setAttribute("cy",centerY);
  }
  ]]>
  </script>


  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
  <circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />


  <script type="text/ecmascript">
  <![CDATA[
  setCoordinates(document.getElementsByClassName("circles"));
  ]]>
  </script>

This simply has no effect. However, when I used "getElementByID" and assigned an ID to the circle, it worked fine. (Opera)

Maurice Tempelsman
  • 895
  • 2
  • 11
  • 13

1 Answers1

6

document.getElementsByClassName returns a collection of elements, so you need to iterate over the results:

var elements = document.getElementsByClassName('circles');

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    setCoordinates(element);
}

Check your JS console if your code doesn't work properly. You should see errors like Object has no method 'setAttribute'.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • But I don't understand where to put this in my SVG code? – Maurice Tempelsman Jan 19 '13 at 14:21
  • And where you've said "elements" plural, do I leave that, but singular "element" I replace it with "circle"? – Maurice Tempelsman Jan 19 '13 at 14:24
  • Sorry but I can't accept this answer without some guidance as to how it fits in. – Maurice Tempelsman Jan 19 '13 at 14:38
  • 1
    @Bushy162: Blender didn't try to fix your code, he tried to help you understand `getElementsByClassName()`. So, in other words: This method does not return a single element but a collection of elements. (The method name already suggests this, see the bold **s** in Blender's reply. Compare with `getElementById()` without "s", which returns one element--or none.) Think of it as an array that holds all the elements with the specified class. If you only have one element with this class, then it's a one element array. – Thomas W Jan 19 '13 at 17:22
  • The theoretical side is sorted. But the practical side doesn't make much sense. I don't see how the code that Blender supplied can work. – Maurice Tempelsman Jan 20 '13 at 12:00
  • 1
    @Bushy162: Take a look at it now. It should work out-of-the-box. – Blender Jan 20 '13 at 15:38
  • Thanks very much, I'll consider my question answered! :) – Maurice Tempelsman Jan 21 '13 at 17:13