생성된 DOM 요소를 제거하는 방법을 알아보겠습니다.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./index.js"/>
</head>
<body>
<p class="text">text</p> <!-- 삭제할 요소 -->
<button>Remove El</button>
</body>
</html>
삭제는 해당 요소를 직접 지우거나 이를 포함하는 다른 요소를 통해서 지우는 방법이 있습니다.
index.js
.remove()를 사용하는 방법 (해당 요소를 직접 삭제)
document.querySelector('button').addEventListener('click', () => {
document.querySelector('.text').remove()
})
.removeChild(target)를 사용하는 방법 (해당 요소의 부모를 활용하는 방법)
document.querySelector('button').addEventListener('click', () => {
document.body.removeChild(document.querySelector('.text'))
})
마무리
이상으로 HTML 요소를 삭제하는 방법을 알아보았습니다.
참고
HTML DOM Element remove Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
HTML DOM Element removeChild Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
Node.removeChild() - Web APIs | MDN
The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.
developer.mozilla.org
Element.remove() - Web APIs | MDN
The Element.remove() method removes the element from the DOM.
developer.mozilla.org
'프론트엔드 > 자바스크립트' 카테고리의 다른 글
프로젝트 - to do (0) | 2022.12.29 |
---|---|
프로젝트 - 뮤직 플레이어 (0) | 2022.12.28 |
배열 안에 객체 밸류 바꾸기 (0) | 2022.12.27 |
드래그 앤 드랍 (0) | 2022.12.26 |
프로젝트 - 가위 바위 보 도마뱀 스폭 게임 (0) | 2022.12.25 |