r1k r1k - 1 year ago 50
CSS Question

how to apply the background from one div to another, in javascript

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

Answer Source

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