-2

I want to fetch an URL-Attribute from a div and my code works perfectly find, except on Safari, where this line:

var url = $('.image').css('background-image').split('url("')[1].split('")')[0];

throws an Error, because the .split-function cannot be executed on an undefined object. Can somebody explain me why Safari does not like this code?

mfaorlkzus
  • 149
  • 3
  • 14
  • The value of the background-image is a link to an s3 file and looks like this: url("...Link Attribute..."). So, I gotta get rid of the url("") part^^ – mfaorlkzus Feb 02 '18 at 14:29
  • Please show a full example of what the `div` would look like. – Scott Marcus Feb 02 '18 at 14:30
  • Ok, well if you really do have it quoted the way you've shown it, you have a problem with nested double quotes. The `url` needs to have single quotes around it. – Scott Marcus Feb 02 '18 at 14:33
  • Well, sorry for the confusion, I added this here to show how the div would work. The link is set within the JQuery code and I use single quotes there `$('.image').css('background-image', 'url(' + data.link + ')');` – mfaorlkzus Feb 02 '18 at 14:38
  • Wouldn't it be better if you just saved `data.link` somewhere else for future reference instead of re-parsing the style? – Federico klez Culloca Feb 02 '18 at 14:39
  • Have you tried looking at what Safari returns when you call `$('.image').css('background-image');`? It might be returning something you weren't expecting and causing issues with your calls to split. – amura.cxg Feb 02 '18 at 14:46
  • Yes, I just did. Turns out that Safari removes the double quotes automatically. Thank you and sorry for wasting your time^^ – mfaorlkzus Feb 02 '18 at 14:49
  • It's not a waste of time if you learned something. Don't forget to mark your questioned answered :) – amura.cxg Feb 02 '18 at 14:57
  • Thank you, I will do that, when the two day period is over. :) – mfaorlkzus Feb 02 '18 at 15:00

1 Answers1

2

So, I figured it out. When you call $('.image').css('background-color') on a browser that is not Safari, you get the following string:

url("http://www.image.com/image1.jpg")

When you call $('.image').css('background-color') using Safari, the following string is returned:

url(http://www.image.com/image1.jpg)
mfaorlkzus
  • 149
  • 3
  • 14
  • I was working on [this fiddle](https://jsfiddle.net/L7j7ke56/1/) of an example solution before you found your answer, figure it might still be helpful – amura.cxg Feb 02 '18 at 15:15