You are here: Reference > JavaScript > client-side > style handling > methods > getAttribute

getAttribute method

Browser support:
Returns the value of the specified style property.
Only Internet Explorer supports the getAttribute method for style properties, in other browsers use the getPropertyValue method instead.
Another possibility to retrieve the value of a CSS property is to use the corresponding JavaScript property. See the example below for details.
If you need to analyze the value of a style property, the getPropertyCSSValue method provides complex functionality in Firefox, Google Chrome and Safari.

Syntax:

object.getAttribute (propertyName [, flags]);
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. 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.
flags
8
Optional. Integer that specifies the case-sensitivity for the name of the property and the type of the returned value.
This parameter is only supported in Internet Explorer earlier than version 8. Since version 8, the name is not case sensitive and the type of the returned value is always a string. In earlier versions, a value of 0 means that the search is case-insensitive and the returned value does not need to be converted.
Other values can be any combination of the following integer constants with the bitwise OR operator:
1
Case-sensitive search.
2
Returns the value as a string.
4
Returns the value as an URL.

Return value:

If no property is specified with the given name, it returns null, else it returns the value of the matching property.

Example HTML code 1:

This example illustrates the use of the getAttribute method:
<head>
    <script type="text/javascript">
        function GetBGColor (button) {
            // Works in all browsers
            alert (button.style.backgroundColor);

            if (button.style.getPropertyValue) {
                alert (button.style.getPropertyValue ("background-color"));
            } else {
                alert (button.style.getAttribute ("backgroundColor"));
            }
        }
    </script>
</head>
<body>
    <button onclick="GetBGColor (this);" style="background-color:red;">Get my background color!</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content