1. DOM(Document Object Model)
2. CRUD(Create-Read-Update-Delete)
Create: 요소 추가하기
Append: 요소를 부모와 연결하기
Read: 요소를 조회하기
Update: 요소를 갱신하기
Delete: 요소를 삭제하기
1. DOM(Document Object Model)
DOM은 html 요소를 객체(object)처럼 조작할 수 있는 모델이다.
HTML은 한번 작성되면 페이지를 옮겨 가지 않는 한 바뀌지 않지만,
DOM을 이용하면 사용자의 행동에 따라 html 요소를 동적으로 조작할 수 있게 된다.
2. CRUD(Create-Read-Update-Delete)
DOM을 이용할 때 가장 기본이 되는 것은 html 엘리먼트를 만들고, 조회하고, 갱신하고, 삭제하는 메서드들이다.
이러한 기본 메서드들을 익힌 다음 좀 더 세부적인 메서드들을 익히면 된다.
Create: 요소 추가하기
document.createElement('div');
새로운 요소를 만든다. 예시의 명령으로 <div> 요소를 만들 수 있다.
Append: 요소를 부모와 연결하기
document.body.append(tweetDiv);
document.createElement()로 생성한 요소는 어떤 노드와도 연결돼 있지 않다.
부모 요소와 연결을 해 줘야 DOM트리 구조에 요소를 넣어 줄 수 있다.
예시에서는 <body>태그의 자식으로 tweetDiv라는 변수명에 할당한 태그를 넣어 주었다.
Read: 요소를 조회하기
//querySelector와 querySelectorAll을 이용해 클래스명으로 요소를 조회하기
const oneTweet = document.querySelector('.tweet')
const tweets = document.querySelectorAll('.tweet')
//getElementById와 querySelector를 이용해 id명으로 요소를 조회하기
const getOneTweet = document.getElementById('container')
const queryOneTweet = document.querySelector('#container')
querySelectorAll 을 사용해서 여러 html 요소들을 한 번에 조회할 경우
그 요소들은 유사 배열로 선택된다. 개별 요소들을 선택하기 위해서는 index값을 넣어준다
Update: 요소를 갱신하기
//textContet로 태그 내부의 텍스트를 변경하기
oneDiv.textContent = 'dev';
console.log(oneDiv) // <div>dev</div>
//classList로 클래스를 추가하거나 제거하기
oneDiv.classList.add('tweet')
console.log(oneDiv) // <div class="tweet">dev</div>
oneDiv.classList.remove('tweet');
console.log(oneDiv) // <div>dev</div>
Delete: 요소를 삭제하기
tweetDiv.remove();
delete 메서드를 사용해 요소를 지울 수 있다.
//innerHTML을 재할당해 자식 요소들을 지우는 방법
document.querySelector('#container').innerHTML = '';
//removeChild로 자식 요소를 지우는 방법
const container = document.querySelector('#container');
while (container.firstChild) {
container.removeChild(container.firstChild);
}
innerHTML로 자식 요소들을 지울 수 있지만, 보안에서 몇 가지 문제가 있다.
removeChild를 이용해도 자식 요소를 지울 수 있다.
예시는 for문을 이용해 container에 자식 요소가 남아 있지 않을 때까지 첫 번째 자식 요소를 지운다.
'Javascript' 카테고리의 다른 글
[Javascript] 클래스와 객체지향 프로그래밍 (0) | 2023.03.15 |
---|---|
[Javascript] 고차함수 (0) | 2023.03.14 |
[Javascript] 구조 분해 할당 (0) | 2023.03.06 |
[Javascript] 스코프와 클로저 (0) | 2023.03.03 |
[Javascript] 원시 자료형과 참조 자료형 (0) | 2023.03.02 |