Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove all HTML elements after the <header> using javascript?

I have a website where, under a certain condition, I want to remove every element after the <header> tag. How can I do this with javascript?

<html lang="en">
<head>
...
</head>
<body>

<main>
        <!-- header start -->
        <header>
        ....
        </header>

    <!--- a bunch of sections, divs, etc that I want to not show sometimes -->


    <!--- But I need these scripts to run, and I want to add my javascript to main.js -->
    <script src="./js/jQuery.js"></script>
    <script src="./js/main.js"></script>

</main>
    

</body>
</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The handy-dandy chainable :not selector could be useful. It doesn’t remove elements by order, as you asked, but maybe it’s a solution here. Otherwise you’ll have to work through the nodeList and check nodeType until you get to a script.

const badEls = document.querySelectorAll('main > :not(header):not(script)');

badEls.forEach(el => {
  el.remove();
});
<body>
  <main>
    <header>Header</header>
    <div>Div</div>
    <section>Section</section>
    <div>Div</div>

    <script src="./js/jQuery.js"></script>
    <script src="./js/main.js"></script>
  </main>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading