JS how can I get css value of multiple elements with the same name and make an array with | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

JS how can I get css value of multiple elements with the same name and make an array with

HTML: <div class = "a"> </div> <div class = "a"> </div> <div class = "a"> </div> CSS: .a:nth-child(1){ background-Image: url("image1.png") } .a:nth-child(2){ background-Image: url("image2.png") } .a:nth-child(3){ background-Image: url("image3.png") } now, with JS, how can I get the background image value of .a and make an array with? So result would look something like this: array = ["image1", "image2", "image3"] https://code.sololearn.com/WobFTCcSz9HO/#js

21st Apr 2020, 3:47 AM
Ginfio
Ginfio - avatar
5 Answers
+ 7
Ginfio Replace everything in your JS tab with the code below to get what you are looking for: window.onload = () => { let images = Array.from( document.querySelectorAll("div.a")).map( item => window .getComputedStyle(item, false) .backgroundImage .match(/url\([\"']([^"')]+)/)[1]); console.log(images); }
21st Apr 2020, 4:30 AM
David Carroll
David Carroll - avatar
+ 2
var x = document.getElementsByClassName("your_class_name"); // x is an array var firstElement = x[0]; // get first element var secondElement = x[1]; // get second element use this __________
21st Apr 2020, 3:56 AM
Ayush Kumar
Ayush Kumar - avatar
+ 1
What are you trying to do ?? also background-Image should be written as background-image
21st Apr 2020, 3:54 AM
Neo Hao Jun
Neo Hao Jun - avatar
0
@Neo Hao Jun I'm trying to get the background image URL of each .a and make an array with them.
21st Apr 2020, 3:56 AM
Ginfio
Ginfio - avatar
0
@TR CodeWorld [AYUSH.ks] I'll need the background-image value of those. background image of x[0], ... x[1].... I've started it in the JS, but it doesn't seem to be working. I tried elem[x].style.backgroundImage
21st Apr 2020, 4:02 AM
Ginfio
Ginfio - avatar