Skip to content Skip to sidebar Skip to footer

Is There A Way To Style Individual Array Elements In Js

I am currently working on a memory game where I have a game board populated with divs created through js. I'm trying to add images to my array values. Here is my array: var memory

Solution 1:

It's .backgroundImage, but your array consists of char values, they don't have the property style. For calling .style, you have to get the DOM element, f.e. with document.getElementById or document.getElementsByClassName. I would recommend to give them class names (.className) and setting the images in css instead of using .style.backgroundImage directly.

Solution 2:

The reason it is not working is because your array elements are strings and not objects. One easy solution would be to make your array like this:

var memory_array = [{name:'A'}, {name:'B'}, ...];

Now, after calling memory_array[0].style-background-image:"SomeImage"; Your first element would become:

{name: 'A',
 style-background-image: "SomeImage"
}

Note that this does not change any style directly. When building DOM elements you will have to call the property style.backgroundImage and apply it to each element

Post a Comment for "Is There A Way To Style Individual Array Elements In Js"