Skip to content
Advertisement

.getAttribute() method on elements returned by querySelectorAll()

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:

<div id="container">
  <div class="box" data-speed="2" id="one"></div>
  <div class="box" data-speed="3" id="two"></div>
  <div class="box" data-speed="4" id="three"></div>
  <div class="box" data-speed="5" id="four"></div>
  <div class="box" data-speed="6" id="five"></div>
</div>

js:

(function() {

var boxes = document.getElementsByClassName("box");

for (var i = 0; i < boxes.length; i++) {

var r = Math.floor((Math.random() * 254) + 1);

boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";

}
})();

var divArray = [];
var divs = document.querySelectorAll(".box");

for (i = 0; i <= divs.length; i++) {

console.log(divs[i]);

var speed = parseInt(divs[i].getAttribute("data-speed"));

};

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

for (i = 0; i < divs.length; i++) {

instead of

for (i = 0; i <= divs.length; i++) {

due to this you are getting last divs[i] as undefined and thats why console display that error

updated fiddle : https://jsfiddle.net/n3qhan4e/

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement