Home >Web Front-end >JS Tutorial >How to set src attribute in javascript
How to set the src attribute in javascript: first use the "document.getElementById("id value")" statement to get the element object; then use the "element object.setAttribute("src","URL address")" statement to add or modify element properties.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript sets src attribute
In javascript, you can use the setAttribute() method to set the src attribute of an element. The code example is as follows:
<img id="img" src="img/1.jpg" / alt="How to set src attribute in javascript" > <p id="demo">点击按钮来设置img图片的 src属性。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { document.getElementById("img").setAttribute("src", "img/3.jpg"); } </script>
Effect Figure:
Description: setAttribute() method
setAttribute() method adds the specified attribute and assigns it Assign the specified value. If this specified property already exists, the value is only set/changed.
Syntax
element.setAttribute(attributename,attributevalue)
Parameters | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you wish to add. |
attributevalue | String | Required. The attribute value you wish to add. |
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to set src attribute in javascript. For more information, please follow other related articles on the PHP Chinese website!