Why does elem.style.backgroundImage return an empty rather than a CSS property?

Why does the following print an empty string for style.backgroundImage? How can I get the height and width of the image so that I can set the div sizes accordingly?

<!DOCTYPE html>
<html>
<head>  
    <link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="myDiv" onclick="outputBGImageUrl(this)">
        Click To Get BG Image Property
    </div>
    <script type="text/javascript">
        function outputBGImageUrl(elem){
            var bgImage = elem.style.backgroundImage;
            console.log(bgImage);
        }
    </script>
</body>
</html>

CSS

.myDiv{
    background-image:url(box.jpg);
}
+3
source share
2 answers

elem.style refers to the inline styles set in the element.

the correct way to get the background image can be found here: Javascript: Get the original <div> URL

It doesn't matter here (with improved url retrieval ;-)).

var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bg_image_url = style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];

And here is how you get the sizes:

var image = new Image();

image.onload = function(){   
    var width = image.width,
    height = image.height;
}

image.src = bg_image_url; //set the src after you have defined the onload callback
+5
source

It returns empty because the background image style must be between brackets ""or''

.myDiv{
background-image:url("box.jpg");
}
0
source

All Articles