Get the App
SLTechnology News&Howtos  ›  Development  › 

How to add and remove HTML elements in JavaScript HTML DOM

Shulou Source: shulou.com Published: 2022-06-01 13:13:18 09月13日 Update

This article mainly introduces how to add and delete HTML elements in JavaScript HTML DOM. It is very detailed and has a certain reference value. Friends who are interested must read it!

HTML DOM node

JavaScript HTML DOM elements (nodes), adding and removing nodes (HTML elements).

Create a new HTML element

To add a new element, first create the element (element node), and then append the element to an existing element.

This is a paragraph.

This is another paragraph.

Var para=document.createElement ("p"); / / create a new

Element var node=document.createTextNode ("this is a new paragraph.") ; / / created a text node para.appendChild (node); / / to

Element appends the newly created text node var element=document.getElementById ("div1"); / / finds an existing element element.appendChild (para); / / appends a new element to the existing element

Delete existing HTML elements

To delete a HTML element, you must first get the parent element of the element:

This is a paragraph.

This is another paragraph.

Var parent=document.getElementById ("div1"); / / find the element var child=document.getElementById ("p1") of id= "div1"; / / find the element of id= "p1"

Element parent.removeChild (child); / / remove child elements from the parent element

Note: this HTML document contains two child nodes (two

Element).

First find the element of id= "div1"

And then find the id= "p1"

element

Finally, delete the child element from the parent element

Tip: deleting an element requires a reference to the parent element. DOM needs to be clear about the element you need to delete, as well as its parent.

Common solution: find the child element you want to delete, and then use its parentNode attribute to find the parent element:

Var child=document.getElementById ("p1"); child [XSS _ clean] .removeChild (child)

HTML DOM tutorial

How to change the content of a HTML element (innerHTML)

How to change the style of HTML elements (CSS)

How to react to HTML DOM events

How to add or remove HTML elements

The above is all the content of the article "how to add and remove HTML elements in JavaScript HTML DOM". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Elements nodes paragraphs this is content two text articles clarity events values interests guys buddies attributes commonly used tutorials documents solutions more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS MariaDB Linux Huawei Shulou Technology