JavaScript getAttribute() methodThe 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. SyntaxParameter Valuesattributename: 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. Example1In 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 NowOutput After the execution, the output is - ![]() After clicking the button, the output will be - ![]() Example2We 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 NowOutput After the execution, the output will be - ![]() After clicking the button, the output is - ![]()
Next TopicJavaScript hide elements
|