Web pages are designed using multiple programming languages. Two such web programming languages are HTML and JavaScript. HTML is a web language used to build the basic structure of web pages, meanwhile, JavaScript is used to include dynamic content to the web pages in order to make them captivating. They both have different distinguishing features that make them stand out. One such feature is HTML DOM. HTML DOM which is short for Document Object Model permits JavaScript to change the content of HTML elements.
For the purpose of changing the attribute value of an HTML element using JavaScript, HTML DOM provides multiple methods. Using these methods you can alter the attribute value of an HTML element in the following ways:
Let’s discuss each of these in detail.
1. Get Attribute
As the name suggests the getAttribute() method is to extract the current value of the attribute. The syntax of the getAttribute() method is as follows.
Syntax of getAttribute() method
Lets see example to further understanding.
Example
Suppose, you want to change src attribute value of <img> element.
The above code shows a Nature picture.
Now we want to change this dog image to a cat image. We use the following code.
The full example with output is shown below.
2. Set Attribute
In order to set an attribute on a specific element, we use the setAttribute() method. It updates the value of an attribute existing on an element or sets a new attribute with a new name and value on an element if one does not exist. The syntax of this method is as follows.
Syntax of setAttribute ( ) method
Let’s see an example to better understand the method.
Example:
First we create a simple button with a label of “Click here”.
Now we have to select the <button> element and we will do that using its id.
Now we will use the setAttribute ( ) method to set new attributes.
btn.setAttribute("enable", " ");
The full code alongwith output is shown below.
<html>
<body>
<button type="button" id="mybtn">Click here</button>
<script>
var btn = document.getElementById("myBtn"); //This selects an element
btn.setAttribute("class", "click-btn"); //This set new attributes
btn.setAttribute("enable", " "); //This sets new attributes
</script>
</body>
</html>
Conclusion
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute. In this tutorial both of these methods are discussed in detail along with suitable examples.