简体   繁体   中英

Remove children from parent Element

My 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>

My JavaScript:

<script>
    $("head").remove();
    $('header').remove();
    $('footer').remove();
    $('div.adv').remove();
    $('script').remove();
</script>

All of the following elements must be removed: "html", "head", "title", "meta", "body", "header", "footer", "main", "script" and "div.adv".

Only the following elements should not be removed: "div.content"

Out:

<div class="content">
    Web Test...!
</div>

In plain JavaScript useElement.remove() :

const ELS_toRemove = document.querySelectorAll('header, footer');  
ELS_toRemove.forEach(EL => EL.remove());

or to be fore specific with your selectors:

"body > header, body > footer"

If you want to re-append one Element ( .content ) whilst removing the contents of the other ones use alsoElement.append() . Contrary to .outerHTML it will preserve all current data and Events of the moved Element.

 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>

You should add JQuery to your HTML code on head .

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Don't forget to put your code below the JQuery import:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
    $("head").remove();
    $('header').remove();
    $('footer').remove();
    $('div.adv').remove();
    $('script').remove();
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM