Is there a DOM function which deletes all elements between two elements in JavaScript?


Let’s say the following are our elements −

<p>My Name is John</p>
<p>My Name is David</p>
<p>My Name is Bob</p>
<p>My Name is Mike</p>
<p>My Name is Carol</p>
<footer>END</footer>

We need to remove the

element and its content. The

elements are in between the START and END.

To remove elements between two elements, use the concept of remove(). Following is the code −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<nav>START</nav>
<p>My Name is John</p>
<p>My Name is David</p>
<p>My Name is Bob</p>
<p>My Name is Mike</p>
<p>My Name is Carol</p>
<footer>END</footer>
<script>
const startingPoint = document.querySelector("nav");
const endingPoint = document.querySelector("footer");
while (startingPoint.nextElementSibling &&
startingPoint.nextElementSibling !== endingPoint) {
   startingPoint.nextElementSibling.remove();
}
</script>
</body>
</html>

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.

Output

This will produce the following output −

Updated on: 07-Sep-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements