简体   繁体   中英

change background image using js

I am not able to change the background image of a division in my project website. I am using this code in js file:

  document.getElementsByClassName("home").style.backgroundImage = "url('../images/background4.jpg')";

my div in html is:

<div id="intro" class='home' align='center'>

also my js file is located in project/js/script.js images are located in project/images/background4.jpg and index.html is in project/index.html

I am not able to find out the mistake!

EDIT

I also tried document.getElementById() but that also doesn't works.

The base path context is defined by index, not by script.js (is not PHP) :

// index.html = ./project/
// execute index.html/js/script.js
// loading index.html/images/background4.jpg
document
  .getElementsByClassName('home')[0]
    .style
      .backgroundImage = "url('images/background4.jpg')";

inscpect DevTools:Network in you browser (right click : inspect).

have nice day.

You have to target your div using document.getElementById('intro') , not getElementsByClassName('home') . getElementsByClassName returns a collection of elements, not an element.

Edit : And yes, as Evehne said, the path should be "images/", not "../images" as you would do in a css file for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM