1

I have an element in a website that looks like this:

<div id="item" style="background-image: url('url to the image')"></div>

Now I need a javascript which extracts only the url of this background-image and replaces it with an url stored in a var.

How is this possible in a "neat" way :) ?

2 Answers 2

2

You could select the div by its id and use setAttribute to set the style attribute to a string containing the new url stored in yourVar like this:

var item = document.getElementById('item');
var newStyle = 'background-image: url(' + yourVar + ');';
item.setAttribute('style', newStyle);
Sign up to request clarification or add additional context in comments.

Comments

1
$('#item').css('background-image', 'url(' + var + ')');

2 Comments

The OP didn't say they were using jQuery. Bit much to expect them to include the whole library just for that...
@LeeTaylor I wouldn't say that's too much to expect. jQuery is quite common along with other similar libraries, but it should be disclosed that this requires jQuery.

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.