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"".
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>
Rendering:
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>
Rendering:
[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!