JavaScript: hasAttribute

The hasAttribute() method checks whether an element has a named HTML attribute and returns a boolean.

What you will learn

Syntax

const exists = element.hasAttribute('attribute-name');

Minimal example

const button = document.querySelector('#save');
if (button && button.hasAttribute('disabled')) {
  console.log('The button is disabled');
}

The result is true when the attribute is present and false when it is absent. For boolean attributes, presence matters even if the value is an empty string.

hasAttribute and getAttribute

Use hasAttribute() when you only need to know whether an attribute exists. Use getAttribute() when you need to read its value. A missing attribute makes getAttribute() return null.

Common mistakes