JavaScript hasAttribute() Method

Summary: in this tutorial, you will learn how to use the JavaScript hasAttribute() to check if an element has an attribute.

Introduction to the JavaScript hasAttribute() method

An attribute is a modifier of an HTML element that controls the element’s behaviors.

An attribute typically consists of a name-value pair specified inside the opening tag of the HTML element.

Generally, an HTML can take any of several most common standard attributes such as id, class, and style. For example:

<div id="message" class="info">HTML attribute</div>Code language: HTML, XML (xml)

To check whether an element has a specified attribute or not, you use the hasAttribute() method:

let result = element.hasAttribute(name);Code language: JavaScript (javascript)

In this syntax:

  • name specifies the attribute name you want to check in the element.

The hasAttribute() returns true if the element contains the specified attribute or false otherwise.

JavaScript hasAttribute() method example

The following example shows how to use the hasAttribute() method to check if the <button> element has the disabled attribute.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS hasAttribute() Demo</title>
</head>
<body>

    <button id="btnSend" disabled>Send</button>

    <script>
        let btn = document.querySelector('#btnSend');
        if (btn) {
            let disabled = btn.hasAttribute('disabled');
            console.log(disabled);
        }
    </script>
</body>
</html>
Code language: HTML, XML (xml)

Output:

trueCode language: JavaScript (javascript)

How it works:

  • Select the button with the id btnSend by using the querySelector() method.
  • Check if the button has the disabled attribute by calling the hasAttribute() method on the <button> element.

Summary

  • Use the hasAttribute() method to check if an element contains a specified attribute.

Quiz

Was this tutorial helpful ?