If you want to use JavaScript to add an image, you can first use the createElement() method to create an img element and assign the URL address value of the image to the src attribute of the img element; then use the appendChild() method to add the img element to Just specify the dom object.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
If you want to use JavaScript to add an image, you can first use the createElement() method to create an img element and assign the URL address value of the image to the src attribute of the img element; then use the appendChild() method to add the img element to Just specify the dom object.
createElement() method
createElement() method creates an element by specifying a name
Syntax:
document.createElement(nodename)
Parameters: nodename :must. Create the name of the element.
Return value: Created element node
getElementById() method
getElementById() method can return the first object with the specified ID citation.
HTML DOM defines multiple methods to find elements, in addition to getElementById(), there are also getElementsByName() and getElementsByTagName().
If there is no element with the specified ID, return null
If there are multiple elements with the specified ID, return undefined.
Syntax:
document.getElementById(elementID)
appendChild() method
The appendChild() method adds a new child node to the end of the node's child node list.
Tip: If newchild already exists in the document tree, it will be removed from the document tree and reinserted in its new position. If newchild is a DocumentFragment node, it will not be inserted directly, but its child nodes will be inserted in order at the end of the childNodes[] array of the current node.
You can use the appendChild() method to remove an element to another element.
Syntax:
node.appendChild(node)
Parameters: node: required. The node object you want to add.
Example: JavaScript to add images to div elements
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript"> window.onload = function() { var bigImg = document.createElement("img"); //创建一个img元素 bigImg.src = "logo.png"; //给img元素的src属性赋值 //bigImg.width="320"; //320个像素 不用加px var myp = document.getElementById('myp'); //获得dom对象 myp.appendChild(bigImg); //为dom添加子元素img }; </script> </head> <body> <div id="myp" style="border:1px solid #eee;width:320px;height:100px;"></div> </body> </html>
[Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to add images in JavaScript. For more information, please follow other related articles on the PHP Chinese website!