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

JavascriptCss

Javascript Problem Overview


How would I get the background-image URL of a <div> element in JavaScript? For example, I have this:

<div style="background-image:url('http://www.example.com/img.png');">...</div>

How would I get just the URL of the background-image?

Javascript Solutions


Solution 1 - Javascript

You can try this:

var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Get the image id, style and the url from it
var img = document.getElementById('testdiv'),
  style = img.currentStyle || window.getComputedStyle(img, false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
console.log('Image URL: ' + bi);

<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>

Edit:

Based on @Miguel and other comments below, you can try this to remove additional quotation marks if your browser (IE/FF/Chrome...) adds it to the url:

bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

and if it may includes single quotation, use: replace(/['"]/g, "")

DEMO FIDDLE

Solution 2 - Javascript

Just to add to this in case anyone else has a similar idea, you could also use Regex:

var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];

However it seems like @Praveen's solution actually performs better in Safari and Firefox, according to jsPerf: http://jsperf.com/match-vs-slice-and-replace

If you want to account for cases where the value includes quotes but are unsure whether it's a double or single quote, you could do:

var url = backgroundImage.slice(4, -1).replace(/["']/g, "");

Solution 3 - Javascript

Try this:

var url = document.getElementById("divID").style.backgroundImage;
alert(url.substring(4, url.length-1));

Or, using replace:

url.replace('url(','').replace(')','');
// Or...
backgroundImage.slice(4, -1).replace(/["']/g, "");

Solution 4 - Javascript

First of all you need to return your background-image content:

var img = $('#your_div_id').css('background-image');

This will return the URL as following:

"url('http://www.example.com/img.png')"

Then you need to remove the un-wanted parts of this URL:

img = img.replace(/(url\(|\)|")/g, '');

Solution 5 - Javascript

const regex = /background-image:url\(["']?([^"']*)["']?\)/gm;
const str = `<div style="background-image:url('http://www.example.com/img.png');">...</div>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Solution 6 - Javascript

Log to console all background-image URLs, without parentheses and quotes:

var element = document.getElementById('divId');
var prop = window.getComputedStyle(element).getPropertyValue('background-image');
var re = /url\((['"])?(.*?)\1\)/gi;
var matches;
while ((matches = re.exec(prop)) !== null) {
    console.log(matches[2]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncelliott1997View Question on Stackoverflow
Solution 1 - JavascriptpalaѕнView Answer on Stackoverflow
Solution 2 - JavascriptsawyerView Answer on Stackoverflow
Solution 3 - JavascriptPraveen Kumar PurushothamanView Answer on Stackoverflow
Solution 4 - JavascriptAlanoud JustView Answer on Stackoverflow
Solution 5 - Javascript武状元 WoaView Answer on Stackoverflow
Solution 6 - JavascriptalissonmullerView Answer on Stackoverflow