Home > Web Front-end > JS Tutorial > body text

How to set img src value in javascript

青灯夜游
Release: 2021-11-03 15:34:47
Original
15741 people have browsed it

Setting method: 1. Use the src attribute of the element object, the syntax "img element object.src="attribute value""; 2. Use the setAttribute() method, the syntax "img element object.setAttribute("src ","Attribute value")".

How to set img src value in javascript

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

javascript sets img src value

Method 1: Use the src attribute of the element object

<!DOCTYPE html>
<html>
	<body>
		<img  src="img/1.jpg"    style="max-width:90%" / alt="How to set img src value in javascript" >
		<p id="demo">点击按钮来改变img标签的内容。</p>
		<button onclick="myFunction()">试一下</button>

		<script>
			function myFunction() {
				var img = document.getElementsByTagName("img")[0];
				img.src = "img/2.jpg";
			}
		</script>
	</body>
</html>
Copy after login

Rendering:

How to set img src value in javascript

Method 2: Use the setAttribute() method

setAttribute() method to add the specified attribute , and assign the specified value to it. If this specified property already exists, the value is only set/changed.

<!DOCTYPE html>
<html>
	<body>
		<img  src="img/1.jpg"    style="max-width:90%" / alt="How to set img src value in javascript" >
		<p id="demo">点击按钮来改变img标签的内容。</p>
		<button onclick="myFunction()">试一下</button>

		<script>
			function myFunction() {
				var img = document.getElementsByTagName("img")[0];
				img.setAttribute("src","img/3.jpg"); 
			}
		</script>
	</body>
</html>
Copy after login

Rendering:

How to set img src value in javascript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to set img src value in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!