I have the following code written in my .js
file:
var tiles = document.querySelectorAll(".tile");
var tileNumbers = ["one", "two", "three", "four"];
for(var i = 0; i < tiles.length; i++){
var num = Math.floor(Math.random() * tileNumbers.lenth);
tiles.classList.add(tileNumbers[num]);
tileNumbers.pop(num);
}
The .tile
are 4 <div>
's in the .html file, and I am trying to add a class each of the four tiles separately. The classes are held in tileNumbers
. When I run the code in Chrome I get the error:
"Uncaught TypeError: Cannot read property 'add' of undefined."
I am pretty sure everything is spelled correctly. Please help!
I have the following code written in my .js
file:
var tiles = document.querySelectorAll(".tile");
var tileNumbers = ["one", "two", "three", "four"];
for(var i = 0; i < tiles.length; i++){
var num = Math.floor(Math.random() * tileNumbers.lenth);
tiles.classList.add(tileNumbers[num]);
tileNumbers.pop(num);
}
The .tile
are 4 <div>
's in the .html file, and I am trying to add a class each of the four tiles separately. The classes are held in tileNumbers
. When I run the code in Chrome I get the error:
"Uncaught TypeError: Cannot read property 'add' of undefined."
I am pretty sure everything is spelled correctly. Please help!
Share Improve this question edited Feb 7, 2017 at 3:23 Golo Roden 151k101 gold badges314 silver badges441 bronze badges asked Feb 7, 2017 at 3:20 Seth HarlaarSeth Harlaar 1282 gold badges3 silver badges15 bronze badges 3 |2 Answers
Reset to default 10You want to call add
on the tile, but try to access the add
function of the tiles
array itself. This does not exist.
What you need to do is to access the add
function of each individual tile. To do so, first get it:
var tile = tiles[i];
Then, change your call to
tile.classList.add(…);
(You could also omit the temporary variable tile
, and use tiles[i].classList.add
directly. But IMHO using a dedicated variable makes the code more clear to read.)
Another option, which may be even better, is to use forEach
. Since you use the i
only for accessing the current element and nothing else, you basically want to perform an action on each element. You can do it like this as well (and, for bonus points, this even protects you against off-by-one errors):
tiles.forEach(function (tile) {
// ...
});
Then, within the function body, you automatically have a variable tile
that you can access in the way you want to.
That's it :-)
tiles[i].classList.add(tileNumbers[num]);
Not
tiles.classList.add(tileNumbers[num]);
tiles
=>tiles[i]
infor()
. – Tushar Commented Feb 7, 2017 at 3:23tileNumbers.lenth
should betileNumbers.length
– user1106925 Commented Feb 7, 2017 at 3:38tileNumbers.pop(num);
doesn't do what you likely think, since the.pop()
doesn't take an argument. You're probably looking for.splice(num, 1)
– user1106925 Commented Feb 7, 2017 at 3:38