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?
JavaScript
x
25
25
1
<html lang="en">
2
<head>
3
4
</head>
5
<body>
6
7
<main>
8
<!-- header start -->
9
<header>
10
.
11
</header>
12
13
<!--- a bunch of sections, divs, etc that I want to not show sometimes -->
14
15
16
<!--- But I need these scripts to run, and I want to add my javascript to main.js -->
17
<script src="./js/jQuery.js"></script>
18
<script src="./js/main.js"></script>
19
20
</main>
21
22
23
</body>
24
</html>
25
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.
JavaScript
1
5
1
const badEls = document.querySelectorAll('main > :not(header):not(script)');
2
3
badEls.forEach(el => {
4
el.remove();
5
});
JavaScript
1
11
11
1
<body>
2
<main>
3
<header>Header</header>
4
<div>Div</div>
5
<section>Section</section>
6
<div>Div</div>
7
8
<script src="./js/jQuery.js"></script>
9
<script src="./js/main.js"></script>
10
</main>
11
</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.
JavaScript
1
16
16
1
// get all siblings of the header element
2
const els = document.querySelectorAll('main > header ~ *');
3
let elsToRemove = [];
4
let i = 0;
5
6
// add all elements to our array until we reach a script
7
do {
8
elsToRemove.push(els[i]);
9
i++;
10
} while (els[i].nodeName !== 'SCRIPT');
11
12
13
// and remove them
14
elsToRemove.forEach(el => {
15
el.remove();
16
});
JavaScript
1
13
13
1
<body>
2
<main>
3
<header>Header</header>
4
<div>Div</div>
5
<section>Section</section>
6
<div>Div</div>
7
8
<script src="./js/jQuery.js"></script>
9
<script src="./js/main.js"></script>
10
11
<div>Div after scripts</div>
12
</main>
13
</body>