EN
JavaScript - get element / node attribute value
0 points
In this article, we would like to show you how to get the element / node attribute value in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#element-id'); // get element by id
2
3
myElement.getAttribute(attributeName); // get the attribute value
In this example, we will get class
attribute value of the myDiv
element using getAttribute()
method.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.blue {
6
background: lightblue;
7
}
8
</style>
9
</head>
10
<body>
11
<div id="my-div" class="blue">This is my div.</div>
12
<script>
13
var myDiv = document.querySelector('#my-div'); // get element by id
14
var attributeValue = myDiv.getAttribute('class'); // get class attribute value
15
console.log(attributeValue);
16
</script>
17
</body>
18
</html>