The content of the img tag is mainly controlled by the src attribute. In JavaScript, you can use the setAttribute() method to set the value of the src attribute of the img tag, and then set the img content. The syntax is "img element object.setAttribute("src" ,"property value")".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer. The
tag defines an image in an HTML page.
tags have two required attributes: src and alt.
The src attribute of the src tag is required. It specifies the URL of the image.
When a web page loads, the browser fetches the image from the web server and inserts it into the page. Therefore, make sure the image is at the same point as the relevant web page, otherwise visitors may get a broken link icon. If the browser cannot find the image, it will display a broken link icon.
javascript sets img content
In javascript, you can use the setAttribute() method to set img content.
The setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.
Example:
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" style="max-width:90%"/ alt="How to set img content in javascript" > <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { document.getElementsByTagName("img")[0].setAttribute("src","img/2.jpg"); } </script> </body> </html>
Rendering:
javascript advanced tutorial]
The above is the detailed content of How to set img content in javascript. For more information, please follow other related articles on the PHP Chinese website!