JavaScript’s Element.hasAttribute() method returns a Boolean value indicating whether the Element has a specified attribute or not.

Syntax

Element.hasAttribute(parameter);

Parameters

A string containing the name of the element’s attribute.

Return value

A Boolean value that is true if the element has the attribute and false if the element does not have the attribute.

Examples

Here is an example of using the JavaScript hasAttribute() method.

Consider the following line of HTML:

<a href="https://javascriptguide.com" target="_blank">JavaScript Guide</a>

How can we make sure that the a element has the href attribute with JavaScript?

Well, we can select the a element with the querySelector() method and use the hasAttribute() method:

let a = document.querySelector('a');
console.log(a.hasAttribute('href'));

You should now be able to see the return value of our method call in the console of your browser.

Browser compatibility

Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
hasAttribute() 1 12 1 8 8 1 18 4 10.1 1 1.0 4.4

See also