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:
xxxxxxxxxx
1
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.
In this example, we will get class
attribute value of the element
using getAttribute()
method.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.blue {
7
background: lightblue;
8
}
9
10
</style>
11
</head>
12
<body>
13
<div id="element" class="blue">This is my div.</div>
14
<script>
15
16
var element = document.querySelector('#element'); // gets element by id
17
18
console.log(element.getAttribute('class')); // prints class attribute value
19
20
</script>
21
</body>
22
</html>