getAttribute()
Introduction to the JavaScript getAttribute()
method
getAttribute()
methodTo get the value of an attribute on a specified element, you call the getAttribute()
method of the element:
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
getAttribute()
exampleConsider the following example:
Output
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
:
Output:
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