Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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?

like image 242
celliott1997 Avatar asked Dec 23 '12 17:12

celliott1997


People also ask

How do you code a background image in Javascript?

backgroundImage = "url('image. png')"; You need to put the relative path to the image from your web page's folder. If the image is located in the same folder, then you can reference it directly inside the url() function as in the code above.

How do I make an image a link in HTML background?

The most common & simple way to add background image is using the background image attribute inside the <body> tag.

Can you put a background image in a div?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.


2 Answers

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

like image 97
palaѕн Avatar answered Oct 02 '22 10:10

palaѕн


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, ""); 
like image 30
sawyer Avatar answered Oct 02 '22 10:10

sawyer