javascriptjqueryhtmlcssmongodb

Get background image url value


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


Solution

  • 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/