728x90
Delete 삭제
DOM을 이용하여 HTML Element를 삭제하는 방법이다.
1. remove
삭제하려는 요소의 위치를 알고 있는경우에 사용
const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)
tweetDiv.remove()
2. innerHTML
모든 자식의 요소를 지울수있다
그러나 보안문제로 사용을 권장하지 않는다
3. removeChild
자식요소를 지정해서 삭제하는 메서드이다
모든 자식요소를 삭제하기 위해 반복문(while, for, etc)을 활용할수있다
const container = document.querySelector('#container');
while (container.firstChild) {
container.removeChild(container.firstChild);
}
이렇게하면 자식요소가 남아있지 않을때까지, 첫번째 자식 요소를 삭제하게된다.
근데 제목까지 삭제하게된다.
const container = document.querySelector('#container');
while (container.children.length > 1) {
container.removeChild(container.lastChild);
}
이렇게하면 container의 자식요소가 1개만 남을때까지, 마지막 자식요소를 제거한다.
4. 직접 클래스 이름이 tweet인 요소만 찾아서 지우는 방법
const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
tweet.remove();
}
for (let tweet of tweets){
tweet.remove()
}
728x90
'부트캠프교육중 > DOM' 카테고리의 다른 글
[DOM] 유효성검사 (회원가입창만들기) (0) | 2023.01.07 |
---|---|
[DOM] 이벤트객체 (0) | 2023.01.07 |
[DOM] Update (0) | 2023.01.06 |
[DOM] Read (0) | 2023.01.06 |
[DOM] Append (0) | 2023.01.06 |