You are here: Reference > JavaScript > client-side > style handling > methods > setAttribute (runtimeStyle, style)

setAttribute method (runtimeStyle, style)

Browser support:
Adds a property with the specified name and value to the current style object.
If a property with the same name exists on the current style object, then it modifies its value.
In other browsers, the setProperty method provides similar functionality. Another possibility to set the value of a CSS property is to use the corresponding JavaScript property. See the examples below for details.

Syntax:

object.setAttribute (propertyName, propertyValue [, caseSens]);
You can find the related objects in the Supported by objects section below.

Parameters:

propertyName
Required. String that specifies the name of the style property to remove. Use the name of the corresponding JavaScript property (camelCase name) instead of the name of the CSS property. The corresponding JavaScript property names can be found on the pages for the CSS properties.
propertyValue
Required. String that specifies the value for the property. In Internet Explorer earlier than version 8, if the property is a custom property, then the value can be an arbitrary object, not only a string.
caseSens
8
Optional. Integer that specifies the case-sensitivity for the name of the property. This parameter is only supported in Internet Explorer earlier than version 8. The name is not case sensitive since version 8. In earlier versions, the following values are supported:
0
The first property with the specified name, regardless of its case, will be overwritten.
1
Default. The first property with the specified name, with respect to its case, will be overwritten.

Return value:

This method has no return value.

Example HTML code 1:

This example illustrates the use of the setAttribute method:
<head>
    <script type="text/javascript">
        function ModifyBGColor (button) {
            if (button.style.setProperty) {
                button.style.setProperty ("background-color", "green", null);
            } 
            else {
                button.style.setAttribute ("backgroundColor", "green");
            }
        }
    </script>
</head>
<body>
    <button onclick="ModifyBGColor (this);" style="background-color:red;">Modify my background color!</button>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example is equivalent to the previous one, but it uses the backgroundColor style property to modify the background color of an element:
<head>
    <script type="text/javascript">
        function ModifyBGColor (button) {
            button.style.backgroundColor = "green";
        }
    </script>
</head>
<body>
    <button onclick="ModifyBGColor (this);" style="background-color:red;">Modify my background color!</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

User Contributed Comments

Post Content

Post Content