hasAttribute()

Introduction to the JavaScript hasAttribute() method

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

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

Parameters

The hasAttribute() method accepts an argument that specifies the name of the attribute that you want to check.

Return value

The hasAttribute() returns a Boolean value that indicates if the element has the specified attribute.

If the element contains an attribute, the hasAttribute() returns true; otherwise, it returns false.

JavaScript hasAttribute() example

See the following example:

<!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:

true
Code 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.

Last updated