Skip to content
Related Articles
Open in App
Not now

Related Articles

How to add/update an attribute to an HTML element using JavaScript?

Improve Article
Save Article
Like Article
  • Last Updated : 23 Jan, 2023
Improve Article
Save Article
Like Article

We can use two approaches to modify an attribute of an HTML element using JavaScript.

Approach 1: 

We can use the inbuilt setAttribute() function of JavaScript.

Syntax: 

var elementVar = document.getElementById("element_id");
elementVar.setAttribute("attribute", "value");

So what basically we are doing is initializing the element in JavaScript by getting its id and then using setAttribute() to modify its attribute.

Example: Below is the implementation of above approach.  

html




<script>
    function modify() {
      
        //update style attribute of element "heading"
      
        var heading = document.getElementById("heading");
        heading.setAttribute("style", "color:green");
      
        //add style attribute to element "tagLine"
      
        var tagLine = document.getElementById("tagLine");
        tagLine.setAttribute("style", "color:blue");
    }
</script>
<h1 style="color:black" id="heading">
    GeeksforGeeks
</h1>
  
<p id="tagLine"> - Society Of Geeks
    <br>
    <br>
    <button onclick="modify()"> Click to modify </button>
</p>

Output: 

How to add/update an attribute to an HTML element using JavaScript?

How to add/update an attribute to an HTML element using JavaScript?

Approach 2:

We can modify HTML attributes even without using setAttribute() function as follows :  

document.getElementById("element_id").attribute = attribute_value;

Example: Below is the implementation of above approach:  

html




<script>
    function add() {
      
        //get the values of fNum and sNum using getAttribute()
      
        var fNum = Number(document.getElementById("fNum").value);
        var sNum = Number(document.getElementById("sNum").value);
        var result = fNum + sNum;
      
        //output the result in green colour
        var output = "Sum of two numbers is " + result;
        document.getElementById("result").style = "color:green";
        document.getElementById("result").innerHTML = output;
      
        /*note the way we have updated innerHTML and added style
        attribute of "result" element */
      
    }
</script>
  
<h1 style="color:green">GeeksforGeeks</h1>
  
<p>
    <b>Enter first number :- </b>
    <input type="number" id="fNum">
    <br>
    <br>
    <b>Enter second number :- </b>
    <input type="number" id="sNum">
    <br>
    <br>
    <button onclick="add()">Add</button>
    <b>
        <p id="result"></p>
    </b>
  
</p>

Output: 

How to add/update an attribute to an HTML element using JavaScript?

How to add/update an attribute to an HTML element using JavaScript?


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!