91

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?

0

9 Answers 9

121

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

Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately this does not work on IE as the string returned is quoted. so I ended up with this: bi = style.backgroundImage.slice(4, -1).replace(/"/g, ""); And now works :)
Firefox quotes the strings too. At least as of FF39.
style.backgroundImage.slice(5, -2) works too of course.
slice?? I feel like a medieval peasant
This is great and answer's OP's question 9 years ago, but be aware that it won't work if backgroundImage has a linear-gradient; e.g.: background-image: linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)), url(https://my.image.com);
28

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, "");

2 Comments

this is complete answer
the | is unrequired in your regex, the [...] means any of chars inside. replace(/["']/g, "") is ok
15

Try this:

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

Or, using replace:

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

5 Comments

This substring just removes the url(. It doesn't remove the quotes. The replace won't work for double quotes. Using the substring and the replace is okay, but won't handle double quotes. backgroundImage.slice(4, -1).replace(/["']/g, ""); is what you're looking for
@narthur157 agreed and updated, but this is a 7 year old answer. 😅
Any more update is needed? Or is it good as it looks? @jave.web Happy to update more. Or go ahead and please update.
@jave.web Just edit the answer, I'll approve it and you will get some points too! 💪🏻
@PraveenKumarPurushothaman ok, since people are still looking to this answer even now-adays - I've done the edit :)
10

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, '');

Comments

1

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}`);
    });
}

Comments

1

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]);
}

Comments

0
  1. Here's a slightly shorter version that is also fool-proof against something like background-image: linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)), url("https://my.image.com"); as suggested by @rpearce but with quotes:
let el = yourTargetElement,
    url = el.style.backgroundImage.replace(/^.+?"|".+?$/g, "");
  1. To account for single quotes as well:
    url = el.style.backgroundImage.replace(/^.+?['"]|['"].+?$/g, "");
  1. More concisely:
    url = el.style.backgroundImage.split(/"|'/)[1];
  1. Or if the url is not quoted:
    url = el.style.backgroundImage.split(/[()]/)[1];

Comments

0

const divElement = document.querySelector('div');

const computedStyle = window.getComputedStyle(divElement);

const backgroundImage = computedStyle.backgroundImage;

const urlMatch = backgroundImage.match(/url(["']?([^"']*)["']?)/);

const backgroundImageUrl = urlMatch ? urlMatch[1] : null;

console.log(backgroundImageUrl);

Comments

0

This is a complete ready to use function. The cool thing is: it automatically removes quotes, if they are there.

const extractBackgroundImageUrl = (element) => {
      const style = window.getComputedStyle(element);
      const imageString = style.backgroundImage;
      const foundUrlRaw = imageString.match(/^url\(?(.+)\)$/i)[1];
      if (!foundUrlRaw) return null;
      const foundUrl = foundUrlRaw.replace(/^['|"| ]*/, "").replace(/['" ]*$/, "");
      if (!foundUrl) return null;
      return foundUrl;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.