Categories
JavaScript Answers

How to get background image URL of an element using JavaScript?

Spread the love

Sometimes, we want to get background image URL of an element using JavaScript.

In this article, we’ll look at how to get background image URL of an element using JavaScript.

How to get background image URL of an element using JavaScript?

To get background image URL of an element using JavaScript, we use the getComputedStyle method.

For instance, we write

const img = document.getElementById("id");
const style = window.getComputedStyle(img, false);
const bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

to get the element with getElementById.

Then we call getComputedStyle to get the computed styles of the element as an object.

Then we write style.backgroundImage.slice(4, -1).replace(/"/g, "") to get the background image URL.

Conclusion

To get background image URL of an element using JavaScript, we use the getComputedStyle method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *