Home >Web Front-end >CSS Tutorial >How to Get a Background Image URL from a Div Element Using JavaScript?
How to Extract Background Image URL of an Element Using JavaScript
In JavaScript, it's possible to retrieve the URL of a background image set on an element dynamically. Here's how:
Q: How can I obtain the background-image URL of a
How do I retrieve the URL of the background image?
A: To retrieve the background image URL, you can use the following code:
var img = document.getElementById('your_div_id'); var style = img.currentStyle || window.getComputedStyle(img, false); var bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
Let's break it down:
Now, bi will contain just the URL of the background image.
For example:
// Get the URL from an element with id "testdiv" var img = document.getElementById('testdiv'); var style = img.currentStyle || window.getComputedStyle(img, false); var bi = style.backgroundImage.slice(4, -1).replace(/"/g, ""); // Display the URL console.log('Image URL: ' + bi);
This will output the URL of the background image to the console.
The above is the detailed content of How to Get a Background Image URL from a Div Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!