1

I'm new to Javascript, but basically what I want to do is get the background from one div's CSS style, and apply it to another div. This is what I have tried but it doesn't work.

NewDiv.style.background = OldDiv.style.background;

I know that I can do:

NewDiv.style.innerHTML = OldDiv.style.inHTML;

But I can't seem to do something similar with the CSS background instead of the html. I'm trying to do it with only javascript and no Jquery

r1k
  • 27
  • 1
  • 5

2 Answers2

0

This should do the trick:

var element1 = document.getElementById("element1Id");
var element2 = document.getElementById("element2Id");
element2.style.background = document.defaultView.getComputedStyle(element1).background;

If you only want a certain portion of the background styling, instead of all at once, you can use any of the options below instead of "background."

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

more information about background styling can be found here

If you are curious why I used "document.defaultView.getComputedStyle" instead of "window.getComputedStyle" feel free to check out this StackOverflow Q/A that answers that question.

TL:DR; "document.defaultView.getComputedStyle" will work in all browsers

Community
  • 1
  • 1
splay
  • 327
  • 2
  • 12
  • thanks, but its not quite what I want to achieve. I dont want to copy all the styles of the first div, just the background. The other styles defines for the second div should stay intact – r1k Oct 04 '16 at 20:42
  • oh gotcha, it's fixed now! – splay Oct 04 '16 at 20:52
0

You can use someElement.style.backgroundColor:

var oldDiv = document.getElementById('old');
var newDiv = document.getElementById('new');

newDiv.style.backgroundColor = oldDiv.style.backgroundColor;

More info: Style backgroundColor Property

DenysM
  • 389
  • 1
  • 2
  • 13