Home>Article>Web Front-end> Add or remove HTML dom elements

Add or remove HTML dom elements

小云云
小云云 Original
2017-11-17 15:11:51 2827browse

The Document Object Model (DOM) is a standard programming interface recommended by the W3C organization for processing extensible markup languages. On a web page, the objects that organize the page (or document) are organized in a tree structure. The standard model used to represent the objects in the document is called DOM. In this chapter, we will share with you how to add or delete HTML dom elements. Tutorial, come and learn now.

Create a new HTML element

To add a new element to the HTML DOM, you must first create the element (element node ), and then appends the element to an existing element.

这是一个段落。

这是另一个段落。

This code creates a new e388a4556c0f65e1904146cc1a846bee element:

var para=document.createElement("p");

To add text to a e388a4556c0f65e1904146cc1a846bee element, you must first create a text node. This code creates a text node:

var node=document.createTextNode("这是一个新段落。");

Then you have to append the text node to the e388a4556c0f65e1904146cc1a846bee element:

para.appendChild(node);

Finally you have to append the new element to an existing element .

This code finds an existing element:

var element=document.getElementById("div1");

The following code adds a new element after an existing element:

element.appendChild(para);

Delete existing HTML Element

这是一个段落。

这是另一个段落。

It would be nice if you could delete an element without referencing the parent element.
But it’s a pity. The DOM needs to know the element you need to delete, and its parent element.

This is a common solution: find the child element you wish to remove, and then use its parentNode attribute to find the parent element:

var child=document.getElementById("p1"); child.parentNode.removeChild(child);

The above is a related tutorial on adding or removing HTML dom elements , hope it can help everyone.

Related recommendations:

How to use DOM to allocate events

The difference between empty and remove in DOM node deletion

jQuery’s method of manipulating DOM

The above is the detailed content of Add or remove HTML dom elements. 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