2

This is my first question ever, please show some love!

I'm trying to grab the background image from a div element and append it to a div every time I push a bottom. Below is the mockup code:

<div class="img"></div>

.img {
background: url("local image file");
}

function addImage(imageSrc) {
  var imageSrc = document.getElementByClassName('img')[0].getComputedStyle.background
}

I could not find a way to grab the local path inside the background url(""). Can someone please help? I only know vanilla Javascript.

Thank you!

3 Answers3

3

Using the getComputedStyle on the window.

const img = document.getElementsByClassName('img')[0];
const url = getComputedStyle(img).backgroundImage.slice(5, -2);

I get the URL from getComputedStyle(element).backgroundImage then slice out the url and brackets surrounding the link

a.mola
  • 3,883
  • 7
  • 23
1

Use:

window.getComputedStyle(document.getElementsByClassName('img')[0]).getPropertyValue('background')
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    Ur sir is almost current, I added .slice(4 , -1) at the end to slice out the url and brackets like the above answer and it worked!!! Thank you, my savior! I truly cannot thank you enough seriously! I've been looking for this answer for two nights. Respect! – SelfTaughtLooking4Job Mar 12 '21 at 03:26
1

getComputedStyle is a property of window. Since window is always implicit, it can be omitted. Here's your solution:

const imgSrc = getComputedStyle(document.querySelector('.img')).backgroundImage.slice(5, -2);
console.log(imgSrc);
.img{
  background:url('test.png');
}
<div class='img'></div>
StackSlave
  • 10,613
  • 2
  • 18
  • 35