Languages
[Edit]
EN

JavaScript - setAttribute() method example

0 points
Created by:
Dirask Community
6300

In this article, we would like to show you how to add an attribute to the element using setAttribute() method in JavaScript.

Quick solution:

element.setAttribute(attributeName, attributeValue);

Where:

  • element - the element to which you want to add the attribute,
  • attributeName - name of the attribute you want to add,
  • attributeValue - value of the attribute you want to add.

 

Practical examples

Example 1

In this example, we will add class attribute to the myDiv element using setAttribute() method.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <head>
    <style>
      .blue {
        background: lightblue;
      }
    </style>
  </head>
  <body>
    <div id="my-div">This is my div.</div>
    <script>
      var myDiv = document.querySelector('#my-div'); // get element by id
      myDiv.setAttribute('class', 'blue');  // add attribute class with 'blue' value 
    </script>
  </body>
</html>

Example 2

In this example, we will add class attribute to the myDiv element using setAttribute() method. The class value will be assigned depending on which button is clicked.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        margin: 5px 5px 5px 15px;
        width: 100px;
        height: 100px;
        border: 1px solid black;
        border-radius: 10px;
        background: lightgray;
      }

      .red-class {
        background: red;
      }

      .green-class {
        background: green;
      }

      .blue-class {
        background: blue;
      }

    </style>
  </head>
  <body>
    <button onclick="colorRed()">red</button>
    <button onclick="colorGreen()">green</button>
    <button onclick="colorBlue()">blue</button>
    <div id="my-div"></div>

    <script>
      var myDiv = document.querySelector('#my-div');

      function colorRed(){
        myDiv.setAttribute('class', 'red-class');
      }

      function colorGreen(){
        myDiv.setAttribute('class', 'green-class');
      }

      function colorBlue(){
        myDiv.setAttribute('class', 'blue-class');
      }
    </script>
  </body>
</html>
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join