Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Set Attributes of individual elements

Set Attributes of individual elements

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
<svg xmlns=""
xmlns:xlink="" width="300" height="300">
<script type="text/ecmascript">
function changeRectColor(evt) {
var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);,"fill",
"rgb("+ red +","+ green+","+blue+")");
<g id="firstGroup">
<rect id="myBlueRect" width="100" height="50" x="40" y="20"
fill="blue" onclick="changeRectColor(evt)"/>
<text x="40" y="100">Click on rectangle to change it's color.</text>

Link to example 3 (set_attributes.svg) – in a separate window)

Setting attributes is very similar to getting attributes. Once the elements are referenced, their method setAttributeNS() can be called. Three arguments are needed: the namespace (in this example null), the attribute name and the attribute value. To calculate random colors, the random generator (a method of the Math object) is used. This method generates a value between zero and one. As the color range is between zero and 255, it is necessary to multiply the randomly generated value by 255. The three random values form the shown RGB fill color of the rectangle.