-1

How can I get reference to the background image object (or reference to it as a node) in JavaScript?

var backgroundImgObject = document. .... ?

Based on this reference, is it possible to get URL of the background image? Any other ways to get URL?

Thank you!

Alex
  • 3,719
  • 7
  • 35
  • 57

1 Answers1

2

Fetch the background Image

var img = document.body.style.backgroundImage;
// Will return url('anyimage.png')

var img = document.body.style.backgroundImage.slice(4, -1);
// Will return anyimage.png

Set the background Image

document.body.style.backgroundImage = "url('anyimage.png')";

In more genral way document.body can be replaced with any DOM object

void
  • 36,090
  • 8
  • 62
  • 107