Home > Web Front-end > JS Tutorial > How to change the src attribute value in javascript

How to change the src attribute value in javascript

青灯夜游
Release: 2023-01-07 11:43:49
Original
8068 people have browsed it

How to change the src attribute value in JavaScript: 1. Use the setAttribute() method, the syntax is "element object.setAttribute("src","attribute value")"; 2. Use the src attribute of HTML DOM, the syntax "ElementObject.src="AttributeValue"".

How to change the src attribute value in javascript

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

javascript changes the src attribute value

Method 1: Use the setAttribute() method

setAttribute () method adds the specified attribute and assigns it the specified value.

Only sets/changes the value if this specified property already exists.

Example:

<!DOCTYPE html>
<html>
<body>

<img  src="img/1.jpg"    style="max-width:90%"/ alt="How to change the src attribute value in javascript" >

<p id="demo">点击按钮来改变img标签src属性的值。</p>

<button onclick="myFunction()">试一下</button>

<script>
function myFunction()
{
document.getElementsByTagName("img")[0].setAttribute("src","img/2.jpg"); 
}
</script>

</body>
</html>
Copy after login

Rendering:

How to change the src attribute value in javascript

2. Use the src attribute of the HTML DOM object

<!DOCTYPE html>
<html>
<body>

<img  src="img/1.jpg"    style="max-width:90%"/ alt="How to change the src attribute value in javascript" >

<p id="demo">点击按钮来改变img标签src属性的值。</p>

<button onclick="myFunction()">试一下</button>

<script>
function myFunction()
{
document.getElementsByTagName("img")[0].src="img/3.jpg"; 
}
</script>

</body>
</html>
Copy after login

Rendering:

How to change the src attribute value in javascript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to change the src attribute 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