Languages
[Edit]
EN

JavaScript - getAttribute() method example

0 points
Created by:
maryam
1061

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.getAttribute(attributeName);

Where:

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

 

Practical example

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

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<head>
  <style>

    .blue {
        background: lightblue;
    }

  </style>
</head>
<body>
  <div id="element" class="blue">This is my div.</div>
  <script>

    var element = document.querySelector('#element'); // gets element by id

    console.log(element.getAttribute('class'));       // prints class attribute value

  </script>
</body>
</html>

Alternative titles

  1. JavaScript - get attribute method example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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