Home  >  Article  >  Web Front-end  >  How to change src path in JavaScript

How to change src path in JavaScript

青灯夜游
青灯夜游Original
2022-01-18 16:24:365416browse

How to change the src path in JavaScript: 1. Use the src attribute of the element object, the syntax "element object.src="new path address";"; 2. Use the setAttribute() method, the syntax "element object. setAttribute("src","new path address");".

How to change src path in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript to change the src path

Method 1: Use the src attribute of the element object

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<img  id="img" src="img/1.jpg"    style="max-width:90%"/ alt="How to change src path in JavaScript" ><br>
		<button onclick="myFunction()">更改src的路径(换图)</button>
		<script>
			function myFunction() {
				var img=document.getElementById("img");
				img.src="img/2.jpg";
			}
		</script>
	</body>
</html>

How to change src path in JavaScript

Method 2: Using the setAttribute() method

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<img  id="img" src="img/1.jpg"    style="max-width:90%"/ alt="How to change src path in JavaScript" ><br>
		<button onclick="myFunction()">更改src的路径(换图)</button>
		<script>
			function myFunction() {
				var img=document.getElementById("img");
				img.setAttribute("src","img/3.jpg");
			}
		</script>
	</body>
</html>

How to change src path in JavaScript

[Related recommendations: javascript learning tutorial

The above is the detailed content of How to change src path in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn