首页 > 解决方案 > 从父元素中移除子元素

问题描述

我的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>

标签: javascripthtml

解决方案


在纯 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>


推荐阅读