javascript - 从父元素中移除子元素
问题描述
我的HTML:
<html>
<head>
<title>Web Test</title>
<meta charset="utf-8" />
<link href="my.css" rel="stylesheet" as="style" media="all">
</head>
<body>
<header>
<div class="navbar">
<a href="#">LINK</a>
</div>
</header>
<main>
<div class="adv">
<a href="#">LINK</a>
</div>
<div class="content">
Web Test...!
</div>
</main>
<footer>
<a href="#">LINK</a>
</footer>
<script>
$(".content head").remove();
...
</script>
</body>
</html>
我的 JavaScript:
<script>
$("head").remove();
$('header').remove();
$('footer').remove();
$('div.adv').remove();
$('script').remove();
</script>
必须删除以下所有元素:“html”、“head”、“title”、“meta”、“body”、“header”、“footer”、“main”、“script”和“div.adv” .
只有以下元素不应被删除:“div.content”
出去:
<div class="content">
Web Test...!
</div>
解决方案
在纯 JavaScript 中使用Element.remove():
const ELS_toRemove = document.querySelectorAll('header, footer');
ELS_toRemove.forEach(EL => EL.remove());
或具体说明您的选择器:
"body > header, body > footer"
如果您想重新附加一个元素 ( .content
) 同时删除其他元素的内容,也可以使用Element.append()。相反,.outerHTML
它将保留移动元素的所有当前数据和事件。
const EL_content = document.querySelector(".content");
const ELS_toRemove = document.querySelectorAll("body > *");
// Remove desired elements:
ELS_toRemove.forEach(EL => EL.remove());
// Add back .content
// .append() will preserve all current data and Events on that element
document.querySelector("body").append(EL_content);
<html>
<head>
<title>Web Test</title>
<meta charset="utf-8" />
<link href="my.css" rel="stylesheet" as="style" media="all">
</head>
<body>
<header>
<div class="navbar">
<a href="#">LINK</a>
</div>
</header>
<main>
<div class="adv">
<a href="#">LINK</a>
</div>
<div class="content">
Web Test...!
</div>
</main>
<footer>
<a href="#">LINK</a>
</footer>
</body>
</html>
推荐阅读
- docker - 将 Vagrant VM 和 Docker 容器连接到同一个桥接网络
- javascript - 如何修复这个简单的手风琴,JavaScript 不工作
- php - 使用 codeigniter 从数据库中检索图像
- java - Java/Selenium - java.lang.NullPointerException
- ios - JSON 未加载到表视图中
- python - 如何使用 python 和 opencv 在实时流中获取当前帧?
- laravel-5.4 - 是否可以将数据存储到控制器的变量中?
- holoviews - 在html中保存holoviews散点图可视化
- javascript - 在 CodeIgniter 使用存储过程中发送数据
- windows - Openssh 突然无法在我的 Windows 上运行