目录
Remove the parent Element of a Node using JavaScript
删除节点的直接父元素
要删除节点的父元素:
- 使用
document.getElementById()
方法选择子节点。 - 使用该
parentElement
属性来访问父元素。 remove()
在父级上
调用该方法,例如child.parentElement.remove()
。
这是此示例的 HTML。
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <!-- 👇️ want to remove this div --> <div> <div id="child">Child 1</div> </div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const child = document.getElementById('child'); child.parentElement.remove();
Node.parentElement
属性返回 DOM 节点的父元素。
parentElement
属性返回null
。如果这是您需要处理的事情,您可以在调用该remove()
方法之前有条件地检查。
const child = document.getElementById('child'); child?.parentElement?.remove();
parentElement
请注意,如果要删除的元素不是直接父元素,则可以多次访问该属性。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- 👇️ Want to remove this Div --> <div> <span> <div id="child">Child 1</div> </span> </div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const child = document.getElementById('child'); child.parentElement.parentElement.remove();
我们两次访问该parentElement
属性以找到div
我们想要删除的元素。
移除父元素而不移除子元素
要删除父元素而不删除其子元素,请
replaceWith()
使用子节点作为参数调用父元素上的方法。
该replaceWith
方法用一组 Node 对象替换元素。
这是示例的 HTML。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="parent" style="background-color: salmon"> <div>Child 1</div> <div>Child 2</div> <div>Child 3</div> </div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const parent = document.getElementById('parent'); parent.replaceWith(...parent.childNodes);
我们使用该document.getElementById()
方法来选择父元素。
然后我们调用
replaceWith
方法用它的子节点替换父元素。
replaceWith
方法将一组Node
或对象作为参数,并用提供的值替换调用它的元素。 DOMString
请注意,我们使用扩展语法 (…) 来解压方法NodeList
调用中的子节点replaceWith
。
replaceWith()
方法需要一个逗号分隔的列表Node
或DOMString
对象。Node.childNodes属性返回
包含元素的子节点的。NodeList
子节点包括:
- DOM 元素
- 文本节点
- 评论
您可能会看到人们使用
children
属性而不是childNodes
,但它们是不同的,因为children
仅返回元素集合,不包括文本节点和注释。
childNodes
属性将返回一个空值NodeList
,我们将删除该元素而不用任何东西替换它。不会抛出任何错误,因此在这种情况下我们不必处理任何特殊的事情。
# 删除节点的间接父元素
要删除节点的间接父元素:
- 使用
document.getElementById()
方法选择子节点。 - 使用
closest()
方法选择间接父元素。 - 调用
remove()
父级上的方法将其删除。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <!-- 👇️ want to remove this div --> <div class="container"> <div> <span> <div id="child">Child 1</div> </span> </div> </div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const child = document.getElementById('child'); const parent = child.closest('div.container'); parent.remove();
closest
方法而不是属性,因为我们试图删除一个不是直接父元素的元素。 parentElement
如果元素本身与选择器匹配,则返回该元素。
如果不存在与提供的选择器匹配的元素,则
closest()
方法返回null
。
该方法采用包含选择器的字符串。提供的选择器可以根据需要指定。
如果向该方法提供了无效的选择器字符串closest()
,
SyntaxError
则抛出一个。
额外资源
您可以通过查看以下教程来了解有关相关主题的更多信息: