getAttribute()

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() 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

How it works:

  • First, select the link element with the id js using the querySelector() 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: JavaScript (javascript)

Summary

  • Get the value of an attribute of a specified element by calling the getAttribute() method on the element.

  • The getAttribute() returns null if the attribute does not exist.

Last updated