0

How can I get URL property value from element defined as

<html>
   <head>
      <style type="text/css">.sprite-thumb {background-image:url(example.jpg);}</style>
   </head>
</html>

I tried $(data).find("header").css("sprite-thumb") but got undefined

4
  • What is the element data? Are you getting the html back from an ajax call? header won't be found as you don't have a header element. You cannot read css properties like that. .css is used to get/set css properties off an element not read the defined properties in your stylesheets. You could grab all elements of class sprite-thumb off your html and read the background-image property with $('.sprite-thumb').css("background-image") but I think you need to define what your ultimate goal is. Commented Nov 7, 2013 at 17:26
  • example of data element is quoted before. in <html>...</html> Commented Nov 7, 2013 at 17:32
  • You don't have a data element in the example above... so $(data) should give you ReferenceError: data is not defined or something similar depending on browser... Commented Nov 7, 2013 at 17:43
  • I have a variable called data in my code, which contains elements quoted in the question. Commented Nov 7, 2013 at 17:45

1 Answer 1

2

You could do this:

var target = $('.sprite-thumb').css('background-image'),
    bg = target.replace(/(^(url\()|\)$)/g,"");

It basically uses .css() jQuery function to retrieve the value for background-image and then remove url( and ) from it, leaving just the url.

FIDDLE

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

2 Comments

this regular expression will remove every occurrence of {,u,r,l,(,) and } characters.
also, at least one element with specified class needs to exist in DOM, otherwise too this won't work.

Your Answer

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