EN
JavaScript - getAttribute() method example
0
points
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>