Home  >  Article  >  Web Front-end  >  How to set img content in javascript

How to set img content in javascript

青灯夜游
青灯夜游Original
2021-07-26 18:28:535942browse

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")".

How to set img content in javascript

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

How to set img content in javascript tag defines an image in an HTML page.

How to set img content in javascript 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:

How to set img content in javascript

##[Recommended learning:

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!

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