47

this is my code

<div style="text-align:center;">
  <div class="ghor" id="a" onclick="chek_mark()"></div>
  function call
</div>
<script type="text/javascript">
  function chek_mark(){
   var el= document.getElementById("a").style.background-image;
   if (el.url("Black-Wallpaper.jpg"))  
   {
     el.url = "cross1.png";
    }
    else if(el.url("cross1.png"))
    {
      alert("<h1>This is working too.</h1>");
     }
   }
</script>

here I want to change the background image using if else condition

this is the style-sheet
.ghor //this is the div class
{
    background-image: url('Black-Wallpaper.jpg');
    background-size: cover;
    border-radius: 5px;
    height: 100px;
    width: 100px;
    box-shadow: 2px 5px 7px 7px white;
    /*background-color: black;*/
    display:inline-block; 
}

i want change the background image of the 'div' which class is 'ghor'

1
  • how can this line var el= document.getElementById("a").style.background-image; work? There's a minus sign in a property... I should have thought it would have to be var el= document.getElementById("a").style.backgroundImage; Commented Apr 12, 2023 at 11:07

9 Answers 9

91

Try this:

document.getElementById('a').style.backgroundImage="url(images/img.jpg)"; // specify the image path here

Hope it helps!

Sign up to request clarification or add additional context in comments.

2 Comments

any chance to manipulate referere here?
if you add semicolon at the end like this document.getElementById('a').style.backgroundImage="url(images/img.jpg);"; it will not work
5

try this one!

var el = document.getElementById("a").style.backgroundImage;
if(el == "url(Black-Wallpaper.jpg)") { // full value is provided
   el.style.backgroundImage = "url(/link/to_new_file.png)"; // change it
}

7 Comments

Will this only get the filename, or will it also get the path?
@Avisari, it will get the value of the background-image css property. If file path is provided, its value will include file path too. Otherwise only the image!
'(/link/to_new_file.png)' what should i write here
it's not working 'var el = document.getElementById('a').backgroundImage; if (el == "url(Black-Wallpaper.jpg)") { //el.style.backgroundImage = "url(cross1.png)"; alert("its working"); }'
Please add ('a').style.backgrounImage instead of simple ('a').backgroundImage. Because background is a property of style of the object not a property of the object.
|
4

You can do it in following ways

STEP 1

   var imageUrl= "URL OF THE IMAGE HERE";
   var BackgroundColor="RED"; // what ever color you want

For changing background of BODY

document.body.style.backgroundImage=imageUrl  //changing bg image
document.body.style.backgroundColor=BackgroundColor //changing bg color

To change an element with ID

document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor 

for elements with same class

   var elements = document.getElementsByClassName("ClassName")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=imageUrl;
        }

Comments

3
//Get the Element from the DOM
var element = document.getElementById("a");

// Change the background image
element.style.backgroundImage = "url('Black-Wallpaper.jpg')"

Comments

2

HTML

<body id="body">
</body>

JavaScript

you can set the time also.

//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds

//images

images[0] = "url(./Images/1.jpg)";
images[1] = "url(./Images/2.jpg)";
images[2] = "url(./Images/3.jpg)";
//function

function changeImage() {
    var el = document.getElementById('body');
    el.style.backgroundImage = images[i];
    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }
    setTimeout('changeImage()', time);
}

window.onload = changeImage;

CSS

overflow-x: hidden;
margin: 0;
padding: 0;
width: 100%;
height: 100vh;
background-repeat: no-repeat;
background-position: center;

1 Comment

Please add an explanation on why this works. Thank you!
2

    

 //Here is an example how to change background image of <div> element using javascript  by feching a new URL form some API.
 // let image teched from API: this is the image you want to put as new background !
// thumbnail image:
// data.picture.thumbnail
//the HTML element whose background needs to be changes is given an id of #thumbnail.

 var thumbUrl = document.querySelector("#thumbnail");
     
//using a function which will update data in the HTML - this is done
//after parsing of the data fetched, I have omitted the steps used for parsing the data.
function updateData(data){
   //data.picture.medium represents our new fetched data containing the URL fo the new image we want to use as background image.
    var newImage=data.picture.medium;
    thumbUrl.style.backgroundImage="url("+newImage+")";
}

Comments

0

//Here is an example how to change background image of element using javascript by feching a new URL form some API.

// let image teched from API: this is the image you want to put as new background !

// thumbnail image:

// data.picture.thumbnail

//the HTML element whose background needs to be changes is given an id of #thumbnail.

var thumbUrl = document.querySelector("#thumbnail");
 

//using a function which will update data in the HTML - this is done

//after parsing of the data fetched, I have omitted the steps used for parsing the data.

function updateData(data){

  //data.picture.medium represents our new fetched data containing the URL fo the new image we want to use as background image.
  var newImage=data.picture.medium;
  thumbUrl.style.backgroundImage="url("+newImage+")";

}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

you can do this

backgroundImage: url(${musics[0].image})

Comments

-3

Bro same problem occured with me🥲. Then I realised that javascript does not work properly when the element's position is fixed or absolute.try changingits position to relative or just remove position property.

1 Comment

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.