How to change the url of the "background" property?

6

I have this function that changes the src of an img:

window.document.images['img'].src = n_src;

<img src="" name="img"/>

But I wanted to change the background url of the style:

<div name="img" style="background: url()"></div>

What is the best way to do this?

    
asked by anonymous 12.10.2015 / 23:25

2 answers

5

To change the background you can use this in JavaScript:

document.querySelector("[name='img']").style.backgroundImage = 'url(...)';

The best thing would be to do this in CSS, but in response to your question you should then use:

  

element .style.backgroundImage = ...

Example: link

    
12.10.2015 / 23:32
5

Modify in this case using the following structure:

var n_src = 'http://arcticmonkeysbr.com/wp-content/uploads/2014/10/maxresdefault1.jpg';


document.querySelector("[name='img']").addEventListener('click', function() {
  this.style.backgroundImage = 'url(' + n_src + ')';
});
div {
  border: 2px solid #000;
  display: block;
  min-height: 100px;
  min-width: 100px;
}
<div name="img"></div>

NOTE: Remove the HTML style attribute, you may be having difficulty overriding the value.

If you are still not able to do so, type console.log (n_src) in the browser console and comment exactly what the value returned.

    
13.10.2015 / 04:35