How to use the setAttribute() In Javascript

The setAttribute() method is used to alter the SVG element’s fill attribute to dynamically change its color by passing the value for this attribute as the second parameter to this method.

Syntax:

element.setAttribute('attributeName', 'value');

Example: The below code implements the setAttribute() method to change color of SVG in JavaScript.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Change SVG color</title>
    <style>
        h2 {
            color: green;
        }
        #element{
            text-align: center;
        }
    </style>
</head>
 
<body style="text-align: center;">
    <h2>w3wiki</h2>
    <svg id='element'>
        <rect id='rectangle' width='100%'
              height='100%' fill='green' />
    </svg><br/><br/>
    <button id="btn">Change Color</button>
    <script>
        let rect =
            document.getElementById('rectangle')
        let btn =
            document.getElementById('btn')
        btn.addEventListener('click', () => {
            rect.setAttribute('fill', 'red')
        })
    </script>
</body>
 
</html>


Output:

How to Change SVG Icon Color on Click in JavaScript ?

SVG stands for Scalable Vector Graphics and is a vector image format for two-dimensional images that may be used to generate animations. The XML format defines the SVG document. You can change the color of an SVG using the below methods:

Table of Content

  • Using the setAttribute()
  • Using style.fill property

Similar Reads

Using the setAttribute()

The setAttribute() method is used to alter the SVG element’s fill attribute to dynamically change its color by passing the value for this attribute as the second parameter to this method....

Using style.fill property

...