I’m trying to get the value of data attributes from multiple div elements. The elements are captured into a variable using
querySelectorAll()
I’m getting an error when I loop through the variable that contains the element and use the getAttribute() Method:
JavaScript
x
8
1
<div id="container">
2
<div class="box" data-speed="2" id="one"></div>
3
<div class="box" data-speed="3" id="two"></div>
4
<div class="box" data-speed="4" id="three"></div>
5
<div class="box" data-speed="5" id="four"></div>
6
<div class="box" data-speed="6" id="five"></div>
7
</div>
8
js:
JavaScript
1
24
24
1
(function() {
2
3
var boxes = document.getElementsByClassName("box");
4
5
for (var i = 0; i < boxes.length; i++) {
6
7
var r = Math.floor((Math.random() * 254) + 1);
8
9
boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";
10
11
}
12
})();
13
14
var divArray = [];
15
var divs = document.querySelectorAll(".box");
16
17
for (i = 0; i <= divs.length; i++) {
18
19
console.log(divs[i]);
20
21
var speed = parseInt(divs[i].getAttribute("data-speed"));
22
23
};
24
Jsfiddle https://jsfiddle.net/kshatriiya/L8xsvzL1/1/
When I
console.log(divs[i])
it shows the element, I don’t know why I’m unable to use the attribute method on it.
Any pointer would be really appreciated!
Advertisement
Answer
Arrays in javascript are 0 index based
use
JavaScript
1
2
1
for (i = 0; i < divs.length; i++) {
2
instead of
JavaScript
1
2
1
for (i = 0; i <= divs.length; i++) {
2
due to this you are getting last divs[i] as undefined and thats why console display that error
updated fiddle : https://jsfiddle.net/n3qhan4e/