JavaScript에서 특정 ID를 가진 요소를 제거하려면 remove() 메서드를 사용하면 됩니다. 이 메서드는 해당 요소를 DOM에서 완전히 삭제하며, 부모 노드를 따로 참조하지 않아도 되어 매우 간편하게 사용할 수 있습니다.
예제
다음은 ID가 "demo"인 h1 요소를 remove() 메서드로 제거하는 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<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>
<body>
<h1 id="demo">Hello</h1>
<p id="demo1">This is my paragraph</p>
</body>
<script>
document.getElementById("demo").remove();
</script>
</html>위 코드에서 핵심은 마지막 스크립트 부분입니다. document.getElementById("demo")로 ID가 "demo"인 요소를 가져온 뒤, .remove()를 호출하여 화면에서 즉시 삭제합니다. 결과적으로 페이지에는 "This is my paragraph" 문단만 남게 됩니다.
실행 방법
위 프로그램을 실행하려면 파일 이름을 anyName.html(또는 index.html)로 저장합니다. 그다음 VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 "Open with Live Server" 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.
출력 결과
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
