Home  >  Article  >  Web Front-end  >  How to add pictures in javascript

How to add pictures in javascript

藏色散人
藏色散人Original
2021-06-26 14:05:065899browse

Javascript method to add an image: First use the createElement() method to create an img element; then assign the URL address value of the image to the src attribute of the img element; finally use the appendChild() method to add the img element to the specified dom in the object.

How to add pictures in javascript

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

How to add pictures with javascript?

createElement() method

createElement() method creates an element by specifying a name

Syntax:

document.createElement(nodename)

Parameters: nodename: required. 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 = "https://www.html.cn/static/images/logo.png"; //给img元素的src属性赋值
//bigImg.width="320";  //320个像素 不用加px
var myp = document.getElementById(&#39;myp&#39;); //获得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: javascript advanced tutorial]

The above is the detailed content of How to add pictures 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