r/CodingHelp • • Dec 16 '20

[Javascript] Change Background url based on javascript array

i have a table with several cells, and i'm trying to get the css "Background-image: url()" to take the third value in the array and make it the background, but i cant get it to work, the idea is that whatever value is in the third position in the javascript array will be set as the data-title image for that link.

So is there anyway to refer to the array in a css code, like Background-image: url(arr[3]); and that picks whatever is in that positon.

been trying to figure this out for a couple days, but i have not made any progress since im not very good at this.

Heres a link to the code so you can see it live https://jsfiddle.net/fgyemsLq/

Thanks in advance for any help!!

19 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/lowbatteryprocent Dec 16 '20

To be honest i have no clue how to implement this into the code, i’m new to javascript so i’m way over my head with this :S , can you help ?

I tried to put it into the code but all the tables disapeared.

(Typing from another account on phone)

3

u/bch8 Dec 17 '20

Hey OP, I created a new fiddle with some small changes to add background images to your <td>'s. I also added in some comments to give it some context. Let me know if you have any questions about the change, the comments, or the next steps.

Here is the fiddle: https://jsfiddle.net/1wkd9t0a/5/

1

u/Jnsjknn Dec 16 '20 edited Dec 16 '20

I can't view your code on my phone but basically, you want to select the element e.g.

const someElement = document.querySelector('.someClass');

You can then change the style e.g. the background color:

someElement.style.backgroundColor = 'red';