HTML DOM Element hasAttribute() Method

Definition and Usage

if the attribute exists, then hasAttribute() The method returns true, otherwise it returns false.

Note:if the specified attribute is explicitly set in the document, or if the document type sets a default value for the attribute,hasAttribute() All methods return true.

See Also:

getAttribute() Method

setAttribute() Method

removeAttribute() Method

hasAttributes() Method

getAttributeNode() Method

setAttributeNode() Method

removeAttributeNode() Method

Tutorial:

HTML Attributes

Example

Example 1

"myButton" has an onclick attribute:

let answer = myButton.hasAttribute("onclick");

Try It Yourself

Example 2

If the <a> element has a target attribute, change the value to "_self":

if (element.hasAttribute("target")) {
  element.setAttribute("target", "_self");
}

Try It Yourself

Syntax

element.hasAttribute(name)

Parameter

Parameter Description
name Required. The name of the attribute.

Return Value

Type Description
Boolean Returns true if the element has an attribute, otherwise false.

Browser Support

element.hasAttribute() is a DOM Level 2 (2001) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support