2

I am trying to get the value of the backgound-image url. The url is set inline directly in the element tag with the style attribute like so

<a style="background-image: url(https:// ....)"></a>

I tried doing

var url = $(this).css('background-image')

with various regexes but it does not seem to work. I am trying to store this URL into MongoDB but I get this error

var styles = parse(el.attribs.style); TypeError: Cannot read property 'attribs' of undefined

henhen
  • 1,038
  • 3
  • 18
  • 36
  • Can you paste in a larger snippet of your javascript? It's unclear what `this` is in your jQuery snippet, and the error you are showing seems to indicate that you are not successfully selecting the element. – dave Mar 08 '17 at 23:22
  • 1
    `el.attribs.style` should be `el.attributes.style` or `el.getAttribute("style")`, but using `$(el).css('background-image')` would be the best way. What's not working about it? – imtheman Mar 08 '17 at 23:25
  • I think what he needs is a regex so he can extract 'https://theurl.com' instead of saving the whole value 'url("https://theurl.com")'. – James Mar 08 '17 at 23:40
  • I tried doing this from another thread about this topic `url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');` but it does not work – henhen Mar 09 '17 at 02:24
  • Does this answer your question? [Get URL from background-image Property](https://stackoverflow.com/questions/6397529/get-url-from-background-image-property) – Jason C Sep 08 '20 at 16:21

2 Answers2

5

Get the style value, then strip the URL from it

var bi = $('a').css("background-image");
alert(bi.split(/"/)[1]);

The call to jQuery .css("background-image") always returns the URL within double quotes, regardless how it was set originally.

Sample fiddle: https://jsfiddle.net/6qk3ufcb/

Joe Salazar
  • 370
  • 4
  • 9
2

In vanilla JS, having full DOM access, it can be done like so:

document.querySelector('a').style.backgroundImage.split('"')[1]

Or, if for whatever reason you don't have DOM access (for example dealing in node, and operating on some simplified HTML parser) it can also be done with regexp:

const htmlString = `<div class="bg-div" style="background-image: url('https://loremipsum.com/imageIpsum.jpg');">`

const reg = /url.'([\w\W]+?)'/;
const searched = reg.exec(htmlString)
console.log(searched[1]) //=> https://loremipsum.com/imageIpsum.jpg
PLW
  • 180
  • 1
  • 12