JavaScript Answers

How to Get the Background Image URL of an Element Using JavaScript?

Spread the love

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('');">...</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, "");  

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:


By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.