Summary: in this tutorial, you will learn how to use the JavaScript getAttribute()
method to get the value of a specified attribute on an element.
Introduction to the JavaScript getAttribute() method
To get the value of an attribute on a specified element, you call the getAttribute()
method of the element:
let value = element.getAttribute(name);
Code language: JavaScript (javascript)
Parameters
The getAttribute()
accepts an argument which is the name of the attribute from which you want to return the value.
Return value
If the attribute exists on the element, the getAttribute()
returns a string that represents the value of the attribute. In case the attribute does not exist, the getAttribute()
returns null
.
Note that you can use the hasAttribute()
method to check if the attribute exists on the element before getting its value.
JavaScript getAttribute() method example
Consider the following example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS getAttribute() Demo</title>
</head>
<body>
<a href="https://www.javascripttutorial.net"
target="_blank"
id="js">JavaScript Tutorial
</a>
<script>
let link = document.querySelector('#js');
if (link) {
let target = link.getAttribute('target');
console.log(target);
}
</script>
</body>
</html>
Code language: HTML, XML (xml)
Output
_blank
Code language: plaintext (plaintext)
How it works:
- First, select the link element with the id
js
using thequerySelector()
method. - Second, get the target attribute of the link by calling the
getAttribute()
of the selected link element. - Third, show the value of the target on the console window.
The following example uses the getAttribute()
method to get the value of the title
attribute of the link element with the id js
:
let link = document.querySelector('#js');
if (link) {
let title = link.getAttribute('title');
console.log(title);
}
Code language: JavaScript (javascript)
Output:
null
Code language: plaintext (plaintext)
Summary
- Get the value of an attribute of a specified element by calling the
getAttribute()
method on the element. - The
getAttribute()
returnsnull
if the attribute does not exist.