Home>Article>Web Front-end> How to add and delete elements in JavaScript

How to add and delete elements in JavaScript

醉折花枝作酒筹
醉折花枝作酒筹 Original
2021-04-08 15:46:06 3635browse

Methods for adding and deleting elements in JS: 1. Use "appendChild("element name")" to add elements; 2. Use "insertBefore(element name, where to add the element)" to add it anywhere Element; 3. Use "removeChild("Element Name")" to delete the element.

How to add and delete elements in JavaScript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

How to add and delete elements in JavaScript

To add an element, you must first create an element. If you want to write in the newly added element To enter text, you need to create a text node, and then insert the value of the text node into the newly added element.

(1) createElement("Element Name"): This method can create a new element. For example: createElement("p") means that a p tag (element/paragraph) is created.

(2) createTextNode("Text Content"): This method can create a text node. For example: createTextNode("I am new content") means that a text node with the value "I am new content" is created.

(3) appendChild("Element Name"): Add a new element. For example: ul.appendChild("li") means adding a li element to ul.

(4) removeChild("Element Name"): Delete an element. The usage is opposite to (3).

The following example dynamically adds the li element to ul, and adds it in front of the original li each time.

 

Note: If you want each newly added li to be in front of the original li, then you need to use theinsertBefore()method.

insertBefore()There are two parameter values in it. The first parameter value is the name of the element you want to add, and the second parameter value is the name of the element where you want to add it ( The value can be null). When it is null, the effect is the same asappendChild().

For example, in the above example, I want the element li added every time to be at the front. Then you only need to change the fourth step:

var Li=UL.getElementsByTagName("li"); UL.insertBefore(li,Li[0]);li.appendChild(text);

That is to say, there are two ways to add a new element: ①appendChild(), ②insertBefore(); delete an element: removeChild()

Recommended learning:javascript video tutorial

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