0

i have problem to fetch background url of a div

HTML:

<div id='test'></div>

CSS:

  #test { position:absolute; height:55px; width:85px; top:554px; left:197px;  background:url('images/1.jpg'); }

when i try to get background image url by using below it displays blank.

alert(document.getElementById("test").style.backgroundImage);

but interestingly it works for following

document.getElementById("test").style.backgroundImage="url('images/1.jpg')";
alert(document.getElementById("test").style.backgroundImage);

Note: No problem with url because image displayed properly

2 Answers 2

1

you can't get the style information from a external CSS since JS only looks into the DOM. I'm not sure if its possible but you should be able to get and modify the CSS information when you set it directly on the element by the style tag:

<div style="position:absolute; height:55px; width:85px; top:554px; left:197px;  background:url('images/1.jpg');"></div>
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it's possible, but you'll need the element always:

function getStyles (element) {
    element = document.getElementById(element);
    if (element.currentStyle) {
        return element.currentStyle;
    } else if (window.getComputedStyle) {
        return document.defaultView.getComputedStyle(element, null);
    }
}

This should return an associative array with all the styles of the given element.

In many cases, funnily enough, it's not possible to access a CSS style directly from JavaScript, as you tried to do.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.