반응형
DOM 이란?
- Document Object Model 의 약어로 웹 문서를 객체화한 것을 말합니다.
- 웹 문서(HTML)를 객체화 함으로써 제어할 수 있습니다.
HTML 요소 선택하기
get 메서드
- document.getElementById : HTML 아이디 명으로 요소를 찾을 수 있습니다.
- document.getElementsByClassName : HTML 클래스 명으로 요소를 찾을 수 있습니다.
- document.getElementsByTagName : HTML 태그명으로 요소를 찾을 수 있습니다.
<!-- HTML -->
<h2 id="title">프론트엔드</h2>
<ul id="list">
<li class="item">html</li>
<li class="item">css</li>
<li class="item">javascript</li>
</ul>
//javascript
document.getElementById('title');
document.getElementsByClassName('item');
document.getElementsByTagName('li');
쿼리 메서드
- CSS 선택자를 사용해 요소를 찾는 메서드입니다.
- document.querySelector : 지정된 선택자에 일치하는 문서 내 첫 번째 요소를 반환합니다. 일치하는 요소가 없으면 null을 반환합니다.
- document.querySelectorAll : 지정된 선택자에 일치하는 요소 목록을 반환합니다.
//javascript
document.querySelector('#title');
document.querySelector('.item');
document.querySelectorAll('.item');
document.querySelectorAll('.item')[1];
HTML 요소 조작하기
콘텐츠 수정
- textContent : 텍스트 데이터만 제공합니다.
- innerHTML : HTML 태그를 그대로 제공합니다.
//javascript
document.getElementById('title').textContent = '프론트엔드!!!';
document.getElementById('title').innerHTML = '<h1>프론트엔드!!!</h1>';
let title = document.getElementById('title');
title.textContent = '프론트엔드@@@';
document.querySelector('body').innerHTML = '<h1>프론트엔드@@@</h1>';
// 지워지고 수정되므로 유의
속성 제어
- setAttribute : 요소에서 주어진 이름의 속성값을 입력합니다.
- getAttribute : 요소에서 주어진 속성의 값을 가져옵니다.
- removeAttribute : 요소에서 주어진 이름의 속성을 제거합니다.
<!-- HTML -->
<form action="#">
<input type="text" name="a">
</form>
//javascript
let input = document.querySelector('input');
input.setAttribute('placeholder','입력해주세요.');
input.setAttribute('required','');
console.log(input.getAttribute('name'));
input.removeAttribute('required');
HTML 요소 스타일링
요소 프로퍼티 직접 수정
- style : style 프로퍼티를 사용하여 직접 수정합니다.
<!-- HTML -->
<p class="hello1">안녕하세요.</p>
//javascript
let hello1 = document.querySelector('.hello1');
hello1.style.color = 'yellow';
hello1.style.background = 'red';
CSS 클래스 이용
- classList : classList 객체를 사용하여 class 를 수정합니다.
<!-- HTML -->
<p id="hello2">안녕하세요.</p>
//CSS
.hello2 {
color: white;
background: black;
}
//javascript
let hello2 = document.querySelector('#hello2');
hello2.classList.add('hello2');
hello2.classList.remove('hello2');
새로운 요소 만들기
innerHTML 속성은 HTML을 추가하지만 기존 내용이 삭제됩니다. 기존 내용을 보존하며 요소를 제어하는 방법을 알아봅시다.
- createElement : 지정한 태그로 HTML 요소를 생성합니다.
let element = document.createElement('p');
- appendChild : 삽입할 요소를 부모 요소의 마지막 자식 요소로 추가합니다.
let hello3 = document.createElement('p');
hello3.textContent = 'Hello';
document.querySelector('body').appendChild(hello3);
- insertBefore : 첫 번째는 삽입할 요소이고 두 번째는 삽입할 위치를 정해는 요소를 지정하여 부모 요소의 특정 위치에 추가합니다.
const hello4 = document.createElement('p');
hello4.textContent = 'World';
document.querySelector('body').insertBefore(hello4, hello3);
// hello3 요소 앞에 hello4를 삽입함
- remove : 해당 요소를 제거합니다.
document.querySelector('.hello1').remove();
- parentNode : 지정된 노드의 부모를 반환합니다.
- children : 지정된 노드의 모든 자식을 반환합니다.
let li = document.querySelector('.item');
console.log(li.parentNode);
let ul = document.querySelector('#list');
console.log(ul.children);
데이터 속성
데이터(data-) 속성을 사용해서 HTML 요소에 임의의 데이터를 추가할 수 있습니다. 브라우저는 데이터 속성을 완전히 무시하므로 자바스크립트에서 쉽게 요소에 속성 값을 활용할 수 있습니다.
dataset
- HTML 요소의 dataset 프로퍼티로 데이터 속성을 읽거나 수정할 수 있습니다.
<!-- HTML -->
<button data-temp="버튼입니다.">버튼</button>
//javascript
const btn = document.querySelector('button')
// 읽기
console.log(btn.dataset.temp); // "버튼입니다." 메시지 출력
// 수정
btn.dataset.temp= '버튼이 아닙니다.';
console.log(btn.dataset.temp); // "버튼이 아닙니다." 메시지 출력
반응형