Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 10 images in the body, and Move button. When i click on Move button, i need to change first and last images. How can i do that?

What I have tried:

I have tried like this`

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Homework 6</title>
	<style>
		#btn1{
			width: 100px;
			height: 30px;
			margin: 50px 0 0 600px;
		}
		.d1{
			float: left;
			margin: 1px;
			width: 130px;
			height: 130px;
			background-size: cover;
		}
	</style>
</head>
<body>
	<div class="d1" style="background-image: url(Images/1.jpg)"></div>
	<div class="d1" style="background-image: url(Images/2.jpg)"></div>
	<div class="d1" style="background-image: url(Images/3.jpg)"></div>
	<div class="d1" style="background-image: url(Images/4.jpg)"></div>
	<div class="d1" style="background-image: url(Images/5.jpg)"></div>
	<div class="d1" style="background-image: url(Images/6.jpg)"></div>
	<div class="d1" style="background-image: url(Images/7.jpg)"></div>
	<div class="d1" style="background-image: url(Images/8.jpg)"></div>
	<div class="d1" style="background-image: url(Images/9.jpg)"></div>
	<div class="d1" style="background-image: url(Images/10.jpg)"></div>
	<button onclick="move()" id="btn1">Move</button>
</body>
<script src="JS/script.js"></script>
</html>




function move(){
	var arr = document.querySelectorAll(".d1")
	arr[0].style.background = url("../Images/10.jpg");
	arr[10].style.background = url("../Images/1.jpg");
}
Posted
Updated 11-Jul-18 8:35am

1 solution

Here is an example on how to change the image with the correct syntax CP_js_changeImage - JSFiddle[^]

The syntax should be
JavaScript
var arr = document.getElementsByClassName("d1");
arr[0].style.backgroundImage  = "url(path to image)";
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900