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!

Checking and Removing Attributes

Checking and Removing Attributes

This section shows how to check for existing attributes and how to remove them.



<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
<script type="text/ecmascript"><![CDATA[
function removeFill(evt) {
var element = evt.target;
if (element.hasAttributeNS(null,"fill")) {
element.removeAttributeNS(null,"fill");
}
else {
alert("This element doesn't have a fill attribute.");
}
}
]]></script>
<g id="firstGroup">
<rect width="70" height="50" x="40" y="5" fill="blue"
onclick="removeFill(evt)"/>
<rect width="70" height="50" x="40" y="65" fill="blue"
onclick="removeFill(evt)"/>
<rect width="70" height="50" x="40" y="125" fill="blue"
onclick="removeFill(evt)"/>
<rect width="70" height="50" x="40" y="185" fill="blue"
onclick="removeFill(evt)"/>
<rect width="70" height="50" x="40" y="245" fill="blue"
onclick="removeFill(evt)"/>
<text x="150" y="30">Click on rectangle<tspan x="150" dy="15">
to remove it's color.</tspan></text>
</g>
</svg>

Link to example 4 (check_remove_attrib.svg) – in a separate window)

To check for the existance of an attribute within an element, the method element.hasAttributeNS() can be used. The arguments are: namespace (null) and attribute name. The method returns true if the attribute exists and false if it doesn’t. The method removeAttributeNS() removes an existing attribute. The arguments are: namespace (null) and attribute name. If the removed attribute is required it will receive the default value as specified in the SVG specification. This is the reason why the rectangles in this example turn black. Here, the attribute is only removed if it exists and if it doesn’t an error message appears.

Comments