Languages
[Edit]
EN

JavaScript - getAttribute() 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 getAttribute() method in JavaScript.

Quick solution:

element.setAttribute(attributeName);

Where:

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

 

Practical example

In this example, we will get class attribute value of the myDiv element using getAttribute() method.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <head>
    <style>
      .blue {
        background: lightblue;
      }
    </style>
  </head>
  <body>
    <div id="my-div" class="blue">This is my div.</div>
    <script>
      var myDiv = document.querySelector('#my-div'); // get element by id
      var attributeValue = myDiv.getAttribute('class');  // get class attribute value
      console.log(attributeValue); 
    </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