HTML DOM的创建,删除及替换
发布日期:2021-05-10 03:51:18 浏览次数:13 分类:精选文章

本文共 1919 字,大约阅读时间需要 6 分钟。

create HTML elements

When working with HTML DOM, sometimes you need to add or modify elements. One common method used for this purpose is document.appendChild().

If you want to add a new element to the DOM, the simplest way is to create the element, add text content if needed, and then append it to an existing parent element. Here's how you can do it:

var newElement = document.createElement("p");var textNode = document.createTextNode("example text");newElement.appendChild(textNode);// Append the new element to a specific divdocument.getElementById("targetDiv").appendChild(newElement);

Adding Elements Before and After

Sometimes you may want to insert an element at a specific position in the DOM. This can be done using the document.insertBefore() method. Here's an example:

var newElement = document.createElement("p");var textNode = document.createTextNode("example text");var targetDiv = document.getElementById("targetDiv");var existingElement = document.getElementById("existingElement");targetDiv.insertBefore(newElement, existingElement);

Removing Elements

To remove an element from the DOM, you can use the document.removeChild() method. Note that you must call this method from the parent element of the element you want to remove:

var parentDiv = document.getElementById("parentDiv");var childElement = document.getElementById("childElement");parentDiv.removeChild(childElement);

Replacing Elements

If you want to replace an existing element with a new one, you can use the document.replaceChild() method. Here's an example:

var parentDiv = document.getElementById("parentDiv");var oldElement = document.getElementById("oldElement");var newElement = document.createElement("span");var textNode = document.createTextNode("new text");parentDiv.replaceChild(newElement, oldElement);

Note: When using replaceAllChild(), the original element is entirely replaced with the new element, including its content.

上一篇:HTML
下一篇:finger

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月16日 15时32分57秒