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

How to add pictures in javascript

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

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

     

[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