Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 두 요소 사이의 모든 요소를 삭제하는 방법 – remove() 활용하기

다음과 같은 HTML 요소들이 있다고 가정해 보겠습니다.

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

이 문서에서는 시작 지점인 <nav>(START) 태그와 끝 지점인 <footer>(END) 태그 사이에 있는 모든 <p> 요소와 그 내용을 삭제해야 합니다.

두 요소 사이의 모든 요소를 제거하려면 JavaScript의 remove() 메서드를 사용하면 됩니다. 핵심 아이디어는 시작 요소의 다음 형제 노드(nextElementSibling)를 계속 확인하면서, 끝 요소가 나타날 때까지 반복적으로 삭제하는 것입니다.

예제 코드

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=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>

위 프로그램을 실행하려면 파일 이름을 “index.html”(또는 anyName.html)로 저장한 후, VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 “Open with Live Server” 옵션을 선택하면 됩니다.

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

JavaScript에서 두 요소 사이의 모든 요소를 삭제하는 방법 – remove() 활용하기

동작 원리 정리

document.querySelector("nav")로 시작 요소를 가져오고, document.querySelector("footer")로 끝 요소를 가져옵니다. 그런 다음 while 반복문 안에서 시작 요소 바로 뒤에 있는 형제 요소가 존재하는지, 그리고 그것이 끝 요소가 아닌지를 검사합니다. 조건이 참이면 remove()를 호출해 해당 요소를 삭제합니다. 이 과정이 반복되면 START와 END 사이에 있던 모든 요소가 깔끔하게 제거되고, 두 기준 요소만 남게 됩니다.