You are here: Reference > JavaScript > client-side > HTML DOM > methods > hasAttribute

hasAttribute method

Browser support:
8
Returns whether the current element has an attribute with the specified name or not.
Note: The hasAttribute method is supported in Internet Explorer from version 8.
In earlier versions of Internet Explorer, use the getAttributeNode method and the specified property.

Syntax:

object.hasAttribute (attributeName);
You can find the related objects in the Supported by objects section below.

Parameters:

attributeName
Required. String that specifies the name of the attribute. The name is case-sensitive in XML documents and case-insensitive in HTML documents.

Return value:

Boolean. One of the following values:
false The current element has no attribute with the specified name.
true The current element has an attribute with the specified name.

Methods for attributes without namespaces:

Name Browser Description
createAttribute
Creates a new attribute node with the specified name.
getAttribute
Returns the value of the attribute with the specified name from the current element.
getAttributeNode
Returns the attribute node with the specified name from the current element.
getNamedItem
Returns the attribute node with the specified name from the current attributes collection.
hasAttribute
8
Returns whether the current element has an attribute with the specified name or not.
removeAttribute
Removes the attribute with the specified name from the current element.
removeAttributeNode
Removes the specified attribute node from the current element.
removeNamedItem
Removes the attribute with the specified name from the current attributes collection and returns the removed attribute node.
setAttribute
Adds an attribute with the specified name and value to the current element.
setAttributeNode
Adds the specified attribute node to the current element.
setNamedItem
Adds the specified attribute node to the current attributes collection.

Example HTML code 1:

This example illustrates the use of the hasAttribute method:
<head>
    <script type="text/javascript">
        function HasIdAttr (button) {
            var hasIdAttr = false;
            if (button.hasAttribute) {
                hasIdAttr = button.hasAttribute ("id");
            } 
            else {
                if (button.getAttributeNode) {
                    var idAttr = button.getAttributeNode ("id");
                    if (idAttr) {
                        hasIdAttr = idAttr.specified;
                    }
                }
            }
            alert (hasIdAttr);
        }
    </script>
</head>
<body>
    <button id="myButton" onclick="HasIdAttr (this)">Has this button an id attribute?</button>
    <button onclick="HasIdAttr (this)">Has this button an id attribute?</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content