- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HTML DOM getAttribute() method
The HTML DOM getAttribute() method is used for getting or setting an attribute associated with a specific HTML element. If the element doesn’t contain the given attribute then this will return null or an empty string.
Syntax
Following is the syntax for getAttribute() method −
element.getAttribute(attributename)
Here, attributename is of type string and is a compulsory parameter. It denotes the attribute name that you want to get value of.
Example
Let us look at an example of the getAttribute() method −
<!DOCTYPE html> <html> <head> <script> function getAttr() { var a = document.getElementsByTagName("a")[0].getAttribute("href"); document.getElementById("Sample").innerHTML = a; } </script> </head> <body> <h1>getAttribute() example</h1> <a href="https://www.google.com">GOOGLE</a> <p>Get the href attribute value of the above link by clicking the below button</p> <button onclick="getAttr()">GET</button> <p id="Sample"></p> </body> </html>
Output
This will produce the following output −
On clicking the GET button −
In the above example −
We have first created an anchor element with href attribute value set to https://www.google.com −
<a href="https://www.google.com">GOOGLE</a>
We have then created a button GET that will execute the getAttr() method on being clicked by the user −
<button onclick="getAttr()">GET</button>
The getAttr() method uses the getElementByTagName() property of the document object to get the first <a> element in our HTML document.
It then gets href attribute value using the getAttribute() method and assigns that value to variable a. This value is then displayed in the paragraph with id “Sample” using its innerHTML property −
function getAttr() { var a = document.getElementsByTagName("a")[0].getAttribute("href"); document.getElementById("Sample").innerHTML = a; }
To Continue Learning Please Login
Login with Google