Seth Harlaar
Seth Harlaar

Reputation: 132

Uncaught TypeError: Cannot read property 'add' of undefined

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!

Upvotes: 3

Views: 59091

Answers (2)

Golo Roden
Golo Roden

Reputation: 150614

You 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 :-)

Upvotes: 10

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93163

tiles[i].classList.add(tileNumbers[num]);

Not

tiles.classList.add(tileNumbers[num]);

Upvotes: 0

Related Questions