SVG - getElementsByClassName
<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>
It just has no effect. However, when I used "getElementByID" and assigned an ID to the circle, it worked fine. (Opera)
+3
source to share
1 answer
document.getElementsByClassName
returns a collection of items, 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 is not working correctly. You should see errors like Object has no method 'setAttribute'
.
+5
source to share