JavaScript’s Element.getAttribute() method returns the value of an attribute of the Element or null if the attribute does not exist.

Syntax

Element.getAttribute(parameter);

Parameters

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

Return value

The getAttribute() method returns a string containing the value of the element’s attribute, except when the attribute does not exist, in which case the method returns null.

Examples

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

Consider the following line of HTML:

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

How can we extract the value of the target attribute with JavaScript?

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

let a = document.querySelector('a');
console.log(a.getAttribute('target'));

You should now be able to see the value of the target attribute (“_blank”) 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)
getAttribute() 1 12 1 5 8 1 18 4 10.1 1 1.0 4.4

See also