저번 글에 이어서 이번에는 DOM요소를 다루는 방법에 대해서 작성해보려고 한다.
[지난 글]
DOM요소를 선택하거나 수정 및 삭제 하는 등의 직접적인 부분부터 CSS를 새롭게 적용해보는, 혹은 태그 내용을 수정해버리는 작업 등을 다뤄볼 예정이다.
1. 태그 내용 변경
태그의 내용을 변경해버리는 작업이다.
총 3가지 방법이 존재한다.
- innerHTML()
- innerText()
- textContent()
개인적으로는 여기서 innerHTML()은 추천하지 않는다. HTML의 태그를 그대로 전달해버려서 보안의 위험성이 존재하기 때문이다.
아래 그림을 통해 이해하면 바로 이해할 수 있을 것이다.

기존에 '안녕하세요'의 내용이 각각의 태그를 통해 변한 모습을 알 수 있는데, innerHTML만 <b></b>태그가 적용되어 글씨가 굵게 표시된 것을 볼 수 있다.
아래는 위 그림과 관련된 코드이다.
const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');
const div3 = document.getElementById('div3');
// [태그 내부 내용 변경]
// 1) innerHTML, innerText, textContent
// - innerHTML: 태그 사용이 가능
// - innerText, textContent: 태그가 문자(기호)로 그대로 노출
div1.innerHTML = '[innerHTML] 여기는 <b>첫 번째</b> 태그';
div2.innerText = '[innerText] 여기는 <b>첫 번째</b> 태그';
div3.textContent = '[textContent] 여기는 <b>첫 번째</b> 태그';
2. 속성 접근
DOM 요소의 속성에도 접근이 가능하다.
아래는 기존에 있던 링크와 이미지가 변하는 것을 보여주는 그림이다.
더 개발자(?)스럽게 이야기하면 <a>태그의 href 속성에 접근하여 링크값을 변경하는 것이고,
<img>태그의 src 속성에 접근하여 이미지 주소값을 변경하는 것이다.

속성에 접근해서 변경된 것을 보여주는 그림이다.
하지만 링크는 육안으로 확인이 되지 않는 것을 볼 수 있는데, 개발자 도구를 통해서 확인해보면 다음과 같다.

위에서 작성한 대로 각각 href, src 속성에 접근해서 각각 #, ../images/temp.png 으로 속성값을 변경한 것을 확인할 수 있다.
이것을 코드로 살펴보면 다음과 같다.
<!-- [HTML 코드] -->
<a href="https://www.naver.com" id="naver">naver</a>
<img src="../images/pooh.png" alt="pooh" id="pooh" />
// [Javascript 코드]
// [속성(attribute)값 변경]
// setAttribute(속성명, 변경할 속성 값) → 속성값을 `설정`하는 메서드
const naver = document.querySelector('#naver');
naver.setAttribute('href', 'https://www.google.com');
const pooh = document.querySelector('#pooh');
pooh.setAttribute('src', '../images/temp.png');
// [속성값 가져오기]
// getAttribute(속성명) → 속성값을 `가져`오는 메서드
console.log(document.querySelector('#pooh').getAttribute('src'));
// ※ 속성 접근(.) 연산자로도 가능
console.log(pooh.id); // pooh
console.log(naver.href); // https://www.google.com/
// ※※ 연산자로 속성에 접근하고, 할당 연산자(=)로 속성값 변경 가능
document.querySelector('#naver').href = '#';
3. CSS 지정하기
DOM 요소의 CSS를 Javascript에서 접근하여 지정하는 것도 가능하다.
두 가지 방법이 존재한다.
참고로 요소를 'Element'라는 이름으로 가정하고 작성했다.
1) Element.style.xxx
style을 적어준 다음 xxx에는 style의 속성을 지정해주면 된다.
다만, 주의할 점은 camelCase를 적용해야 한다는 것이다.
예를 들어 background-color의 경우, backgroundColor로 사용하면 된다.
2) Element.classList.xxx
두 번째 방법으로는 classList로 class를 추가하는 방법이다.
class에 해당하는 CSS를 작성해서 class를 붙여주거나 빼거나 하는 등의 방법이다.
- classList.add
- classList.remove
- classList.contains
- classList.toggle
두 가지 방법 모두 자세한 것은 아래 코드를 통해 참고하면 된다.
// [CSS 지정]
const h1 = document.querySelector('h1');
const list = document.querySelectorAll('ul > li'); // 유사 배열
// 1) style 속성
// style이라는 속성을 이용해서, css 지정 가능
// style.XXX (xxx: camelCase)
// list[0].style.backgroundColor = 'purple';
// list[0].style.fontSize = '20px';
// list[0].style.color = '#fff';
for (let li of list) {
li.style.backgroundColor = 'purple';
li.style.fontSize = '20px';
li.style.color = '#fff';
}
// 2) classList 활용
// xxx.classList.add
// xxx.classList.remove
// xxx.classList.contains: 있는지 없는지 확인(true / false)
// xxx.classList.toggle: 있으면 제거, 없으면 추가
h1.classList.remove('add-h1');
h1.classList.add('add-h1');
console.log(h1.classList.contains('add-h1')); // true
if (h1.classList.contains('add-h1')) {
h1.innerText = '하하하 add-h1 클래스가 있지요!';
} else {
h1.innerText = '우우우 add-h1 클래스가 없지요!';
}
h1.classList.toggle('add-h1');
console.log('--------------');
4. 요소 찾기, 생성, 추가, 삭제
원하는 요소를 찾거나 요소를 생성/추가/삭제 하는 등의 조작도 가능하다.
1) 요소 찾기
// [요소 찾기]
// 계층 구조 (형제, 자식, 부모, 조상, 자손)
const friends = document.querySelector('#friends');
const tigger = document.querySelector('#tigger');
// 1) 자식 요소
console.log(friends.children); // HTMLCollection → 유사배열
console.log(friends.children[0]);
// 2) 부모 요소
console.log(tigger.parentNode);
// 3) 형제 요소
console.log(tigger.previousElementSibling); // 이전 → 이요르
console.log(tigger.nextElementSibling); // 이후 → 피글렛
console.log(tigger.nextElementSibling.nextElementSibling); // 이후의 이후 → 로빈
console.log(tigger.parentNode.parentNode); // <body> → #tigger의 부모인 <ul>의 부모인 <body>
위 코드는 요소를 찾는 코드이다.
요소는 찾고자 하는 '그 요소'일 수도 있지만, 찾고자 하는 요소의 부모(상위) 및 자식(하위) 요소에도 접근이 가능하다.
- 자식 요소
- Element.children
- Element.children
- 부모 요소
- Element.parentNode
- Element.parentElement
- 형제 요소
- Element.previousElementSibling (이전 형제 요소)
- Element.nextElementSibling (이후 형제 요소)
2) 요소 생성
// (1) 요소 생성
const container = document.querySelector('.container');
const p = document.createElement('p'); // 요소 생성 → <p></p> 태그 생성
p.innerText = '새로 추가된 p 요소 입니다.';
p.style.fontWeight = 'bold';
p.style.backgroundColor = '#f00';
요소를 생성할 때는 3가지만 기억하면 된다.
- 요소 찾아서 지정하기
- 여러 가지 방법이 있지만 document.querySelector를 사용했다.
- 여러 가지 방법이 있지만 document.querySelector를 사용했다.
- 요소 생성
- document.createElement(생성하고자 하는 태그)
- document.createElement(생성하고자 하는 태그)
- 요소에 css, 속성/속성값, 화면에 보여줄 문자 지정
3) 요소 추가
요소 추가는 처음에 추가할지, 마지막에 추가할지를 정해주면 된다.
처음에 추가할 때는 prepend를, 마지막에 추가하고 싶을 때는 append를 사용하면 된다.
- append
- prepend
// (2) 요소 추가
// - x.append(y): `x`요소의 맨 마지막 자식으로 `y`요소 추가 → 여러 개 요소 추가 가능
// - x.appendChild(y): append와 똑같으나 하나의 요소만 추가할 수 있다.
// container.append(p);
div1.appendChild(p);
const p2 = document.createElement('p');
const p3 = document.createElement('p');
p2.innerHTML = 'p2';
p3.innerHTML = 'p3';
p2.classList.add('p-2');
p3.classList.add('p-3');
container.append(p2, p3); // 여러 개 추가도 가능
// - x.prepend(y): `x`요소의 맨 처음 자식으로 `y`요소 추가
const li1 = document.createElement('li');
li1.textContent = '캉가';
friends.prepend(li1);
const li0 = document.createElement('li');
li0.innerHTML = '<b>친구들을 소개합니다.</b>';
friends.prepend(li0);
4) 요소 삭제
요소를 삭제할 때는 remove를 사용하면 된다.
// (3) 요소 삭제
// - x.remove(): `x`요소를 삭제
const firstLi = document.querySelector('li'); // 가장 처음있는 li선택
console.log(firstLi); // <li><b>친구들을 소개합니다.</b></li>
// firstLi.remove();
// - x.removeChild(y): `x`의 자식요소인 `y`를 삭제
const ul = firstLi.parentNode; // ul 태그
ul.removeChild(firstLi);
// firstLi.remove()와 동일한 코드이다.