To get the background image URL of an element using JavaScript, we can use the getComputedStyle method to get the value of the background-image CSS property.
For instance, if we have the following HTML:
<div style="background-image:url('http://www.example.com/img.png');">...</div>
Then we can get the value of the background-image CSS property in the style tag by writing:
const div = document.querySelector('div')
const style = window.getComputedStyle(div, false)
const bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
console.log(bi)
We get the div with document.querySelector .
Then we call window.getComputedStyle with div to get the CSS style values of the div in an object.
To get the background-image CSS property value, we use the style.backgroundImage property.
And then we call slice to extra the URL part of the image and replace to replace the quotation marks from the string.
Therefore, bi is:
'https://www.example.com/img.png'