Javatpoint Logo
Javatpoint Logo

JavaScript getAttribute() method

The getAttribute() method is used to get the value of an attribute of the particular element. If the attribute exists, it returns the string representing the value of the corresponding attribute. If the corresponding attribute does not exist, it will return an empty string or null.

It is different from the getAttributeNode() method. The getAttributeNode() method returns the attribute as an Attr object.

Syntax

Parameter Values

attributename: It is the required parameter. It is the name of the attribute we want to get the value from.

Let us understand it by using some examples.

Example1

In this example, there are two div elements with id div1 and div2, each having style attribute. We are getting the value of style attribute by using the getAttribute() method.

We have to click the given button to get the value of the style attribute of given div elements.

Test it Now

Output

After the execution, the output is -

JavaScript getAttribute() method

After clicking the button, the output will be -

JavaScript getAttribute() method

Example2

We can also get the value of onclick attribute of the button element. In this example, we are extracting the value of onclick attribute and the value of href attribute. There is an anchor element with the href attribute; we are getting this attribute's value using the getAttribute() method.

Test it Now

Output

After the execution, the output will be -

JavaScript getAttribute() method

After clicking the button, the output is -

JavaScript getAttribute() method




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA