Skip to content
Advertisement

How to remove all HTML elements after the using javascript? [closed]

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>

Advertisement

Answer

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.

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>

Otherwise you’ll have to work through the nodeList and check nodeType until you get to a script. This would be safer if you have other elements after the scripts.

// get all siblings of the header element
const els = document.querySelectorAll('main > header ~ *');
let elsToRemove = [];
let i = 0;

// add all elements to our array until we reach a script
do {
  elsToRemove.push(els[i]);
  i++;
} while (els[i].nodeName !== 'SCRIPT');


// and remove them
elsToRemove.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>

    <div>Div after scripts</div>
  </main>
</body>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement