● DOM (Document Object Model) : HTML 요소를 Object(JavaScript Object)처럼 조작할 수 있는 모델
☞ HTML에 JavaScript 적용하기
<script src="같은 디렉토리에 존재하는 js파일 이름"></script>
// <body> 요소가 끝나기 전에 삽입
// (참고) 웹 브라우저가 HTML 해석 중 <script> 요소를 만나게 되면, <script> 요소를 먼저 실행한다.
- 자바스크립트에서 DOM은 document 객체에 구현되어 있다.
DOM을 객체의 모습으로 출력하는 console.dir을 이용하여 document.body를 조회할 수 있다.
console.dir(document.body)
자식 엘리먼트를 찾으려면 console.dir(document.body)를 통해 출력된 객체에서 children속성을 찾거나,
document.body.children을 입력해 바로 조회하면 된다.

CRUD (Create, Read, Update, Delete)
document 객체를 통해 HTML 엘리먼트를 만들고(Create), 조회하고(Read), 갱신하고(Update), 삭제하는(Delete) 방법 실습 ↓↓↓


DOM으로 HTML 엘리먼트의 정보를 조회(Read)하기 위해서는 querySelector의 첫 번째 인자로 셀렉터(selector)를 전달하여 확인할 수 있다. 셀렉터로는 HTML 요소("div"), id("#tweetList"), class(.tweet) 세 가지가 가장 많이 사용된다.
const oneTweet = document.querySelector('.tweet')
//클래스 이름이 tweet인 HTML 요소 중 첫 번째 요소를 조회
const tweets = document.querySelectorAll('.tweet')
//querySelectorAll을 사용하면,
//클래스 이름이 tweet 인 모든 HTML 요소를 유사 배열(Array-like Object)로 받아온다.
(참고) 오래된 DOM 조회 메서드로 getElementId와 같이 get으로 시작하는 것들도 있다.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

마지막으로 삭제(Delete)하는 방법
const container = document.querySelector('#container')
const tweetDiv = document.createElement('div')
container.append(tweetDiv)
tweetDiv.remove() // 삭제하려는 요소의 위치를 알고 있는 경우
document.querySelector('#container').innerHTML = '';
// id가 container인 요소 아래의 모든 요소 지우기
// 여기서 사용된 innerHTML은 보안상 문제가 있다.
// 그러므로 사용하게 되는 게 removeChild.
// removeChild 는 자식 요소를 지정해서 삭제하는 메서드이다.
// 모든 자식 요소를 삭제하기 위해 반복문을 활용할 수 있다.
const container = document.querySelector('#container');
while (container.firstChild) {
container.removeChild(container.firstChild);
} // container의 첫 번째 자식 요소가 존재하면 첫 번째 자식 요소를 제거
// 모든 요소를 삭제하는 것이 아닌 특정 요소는 남기고 삭제하고 싶은 경우라면,
// 자식 요소가 담고 있는 문자열을 비교해 특정 문자열이 있는 요소만 남기거나,
// 새로운 변수를 생성하고 특정 요소를 할당해뒀다가 반복문이 끝난 뒤에 새롭게 추가할 수 있다.
const container = document.querySelector('#container');
while (container.children.length > 1) {
container.removeChild(container.lastChild);
} // 이렇게 하면 container의 마지막 자식 요소 1개만 남게 할 수도 있다.
const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
tweet.remove();
})
// or
for (let tweet of tweets){
tweet.remove()
}
// 클래스 이름이 tweet인 요소만 찾아서 제거하는 법
'22.12.15 ~ 23.06.08 코드스테이츠' 카테고리의 다른 글
| [JS/Node] 비동기(1) (0) | 2023.01.19 |
|---|---|
| [JavaScript] 고차 함수 (0) | 2023.01.13 |
| JavaScript Koans (0) | 2023.01.04 |
| [JavaScript] ES6 주요 문법 (0) | 2023.01.04 |
| [JavaScript] 클로저 (0) | 2023.01.04 |
댓글