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