요소 선택과 조작
              
          2025. 3. 30. 22:39ㆍWeb Development/JavaScript
요소 선택과 조작
DOM을 다룰 때 첫 번째 단계는 조작하고자 하는 요소를 선택하는 것입니다. JavaScript는 다양한 요소 선택 방법을 제공합니다.
요소 선택 메서드
단일 요소 선택
// ID로 요소 선택 (단일 요소 반환)
const header = document.getElementById('header');
// CSS 선택자로 첫 번째 일치하는 요소 선택
const firstParagraph = document.querySelector('p');
const activeElement = document.querySelector('.active');
const formElement = document.querySelector('#contact-form');
const nestedElement = document.querySelector('ul li.special');
여러 요소 선택
// 태그 이름으로 요소 선택 (HTMLCollection 반환)
const allParagraphs = document.getElementsByTagName('p');
// 클래스 이름으로 요소 선택 (HTMLCollection 반환)
const menuItems = document.getElementsByClassName('menu-item');
// CSS 선택자로 모든 일치하는 요소 선택 (NodeList 반환)
const buttons = document.querySelectorAll('button');
const activeItems = document.querySelectorAll('.active');
const formInputs = document.querySelectorAll('#contact-form input');
HTMLCollection과 NodeList의 차이
// HTMLCollection은 "live" 컬렉션 (DOM 변경 실시간 반영)
const paragraphs = document.getElementsByTagName('p');
// NodeList는 일반적으로 "static" 컬렉션 (단, 일부 예외 있음)
const paragraphList = document.querySelectorAll('p');
// 새 단락 추가
const newParagraph = document.createElement('p');
document.body.appendChild(newParagraph);
console.log(paragraphs.length); // HTMLCollection 길이 증가
console.log(paragraphList.length); // NodeList 길이 유지
// HTMLCollection은 배열이 아니라서 배열 메서드를 바로 사용할 수 없음
// Array.from()이나 전개 연산자로 배열로 변환 가능
Array.from(paragraphs).forEach(p => {
  p.style.color = 'blue';
});
// NodeList는 forEach를 지원하지만 다른 배열 메서드는 지원하지 않음
paragraphList.forEach(p => {
  p.style.fontWeight = 'bold';
});
요소 관계 탐색
DOM 요소들 간의 관계를 이용하여 요소를 탐색할 수 있습니다.
const list = document.querySelector('ul');
// 자식 노드 탐색
console.log(list.childNodes); // 텍스트 노드 포함한 모든 자식 노드 (NodeList)
console.log(list.children); // 요소 노드만 포함 (HTMLCollection)
console.log(list.firstChild); // 첫 번째 자식 노드 (텍스트 노드 가능)
console.log(list.firstElementChild); // 첫 번째 자식 요소 노드
console.log(list.lastChild); // 마지막 자식 노드
console.log(list.lastElementChild); // 마지막 자식 요소 노드
// 부모 노드 탐색
const listItem = document.querySelector('li');
console.log(listItem.parentNode); // 부모 노드
console.log(listItem.parentElement); // 부모 요소 노드
// 형제 노드 탐색
console.log(listItem.previousSibling); // 이전 형제 노드 (텍스트 노드 가능)
console.log(listItem.previousElementSibling); // 이전 형제 요소 노드
console.log(listItem.nextSibling); // 다음 형제 노드
console.log(listItem.nextElementSibling); // 다음 형제 요소 노드
요소 콘텐츠 조작
선택한 요소의 내용을 다양한 방식으로 조작할 수 있습니다.
const paragraph = document.querySelector('p');
// textContent: 요소의 모든 텍스트 콘텐츠 (태그 무시, 숨겨진 요소 포함)
console.log(paragraph.textContent); // 모든 텍스트 내용
paragraph.textContent = '새로운 텍스트 내용'; // 텍스트 변경
// innerHTML: HTML을 포함한 요소의 내용
console.log(paragraph.innerHTML); // HTML 포함 내용
paragraph.innerHTML = '새로운 내용 <strong>강조</strong>'; // HTML 변경
// innerText: 화면에 표시되는 텍스트 (CSS 고려, 숨겨진 요소 제외)
console.log(paragraph.innerText); // 표시되는 텍스트
paragraph.innerText = '새 텍스트'; // 텍스트 변경 (HTML 태그가 이스케이프됨)
// outerHTML: 요소 자체를 포함한 HTML
console.log(paragraph.outerHTML); // 요소 자체 포함 HTML
paragraph.outerHTML = '<div>완전히 새로운 요소</div>'; // 요소 자체를 교체
요소 속성 조작
요소의 속성(attribute)을 읽고 수정할 수 있는 여러 방법이 있습니다.
const link = document.querySelector('a');
// 표준 속성은 직접 접근 가능
console.log(link.href); // href 속성 값
link.href = 'https://www.example.com'; // href 속성 변경
console.log(link.id); // id 속성 값
link.id = 'main-link'; // id 속성 변경
// getAttribute/setAttribute 메서드
console.log(link.getAttribute('target')); // target 속성 값 가져오기
link.setAttribute('target', '_blank'); // target 속성 설정
link.setAttribute('data-test', 'value'); // 사용자 정의 데이터 속성 설정
// 속성 존재 확인 및 제거
console.log(link.hasAttribute('rel')); // rel 속성 존재 여부
link.removeAttribute('rel'); // rel 속성 제거
// 데이터 속성(dataset)
console.log(link.dataset.test); // data-test 속성 접근
link.dataset.info = '추가 정보'; // data-info 속성 설정
요소 스타일 조작
요소의 스타일을 직접 변경하거나 클래스를 조작하여 스타일을 변경할 수 있습니다.
const element = document.querySelector('#my-element');
// 인라인 스타일 직접 조작
element.style.color = 'red';
element.style.backgroundColor = 'black'; // 카멜 케이스로 속성명 작성
element.style.padding = '10px';
element.style.border = '1px solid blue';
// 여러 스타일 한 번에 설정
Object.assign(element.style, {
  margin: '20px',
  fontSize: '16px',
  textAlign: 'center'
});
// 현재 계산된 스타일 가져오기
const computedStyle = window.getComputedStyle(element);
console.log(computedStyle.color); // RGB 형식의 색상 값
console.log(computedStyle.fontSize); // 픽셀 단위의 폰트 크기
// 클래스 조작
element.className = 'highlight'; // 클래스 교체
element.className += ' active'; // 클래스 추가 (공백 주의)
// classList API (더 편리함)
element.classList.add('visible'); // 클래스 추가
element.classList.remove('highlight'); // 클래스 제거
element.classList.toggle('active'); // 클래스 토글 (있으면 제거, 없으면 추가)
console.log(element.classList.contains('visible')); // 클래스 존재 여부 확인
element.classList.replace('visible', 'hidden'); // 클래스 교체
요소 생성 및 추가
새로운 요소를 생성하고 문서에 추가하는 방법입니다.
// 새 요소 생성
const newDiv = document.createElement('div');
newDiv.textContent = '새로 생성된 div 요소';
newDiv.className = 'new-element';
newDiv.id = 'unique-id';
// 문서에 요소 추가
document.body.appendChild(newDiv); // body의 마지막 자식으로 추가
// 특정 위치에 요소 삽입
const referenceElement = document.querySelector('#reference');
document.body.insertBefore(newDiv, referenceElement); // 참조 요소 앞에 삽입
// 현대적인 삽입 메서드들
referenceElement.after(newDiv); // 참조 요소 뒤에 삽입
referenceElement.before(newDiv); // 참조 요소 앞에 삽입
referenceElement.append(newDiv, document.createTextNode(' 추가 텍스트')); // 마지막 자식으로 여러 노드 추가
referenceElement.prepend(newDiv); // 첫 번째 자식으로 추가
referenceElement.replaceWith(newDiv); // 참조 요소 대체
// innerHTML로 여러 요소 한번에 추가 (주의: 보안 이슈 가능성)
const container = document.querySelector('.container');
container.innerHTML = `
  <h2>새로운 제목</h2>
  <p>새로운 문단 내용입니다.</p>
  <button>클릭하세요</button>
`;
// DocumentFragment 사용 (성능 최적화)
const fragment = document.createDocumentFragment();
for (let i = 0; i < 10; i++) {
  const li = document.createElement('li');
  li.textContent = `항목 ${i + 1}`;
  fragment.appendChild(li);
}
document.querySelector('ul').appendChild(fragment); // 한 번의 DOM 업데이트만 발생
요소 복제 및 삭제
기존 요소를 복제하거나 삭제하는 방법입니다.
// 요소 복제
const original = document.querySelector('#original');
const clone = original.cloneNode(); // 얕은 복제 (속성만 복제)
const deepClone = original.cloneNode(true); // 깊은 복제 (자식 노드 포함)
document.body.appendChild(deepClone); // 복제본을 문서에 추가
// 요소 삭제
const elementToRemove = document.querySelector('#remove-me');
elementToRemove.remove(); // 현대적인 방법
// 레거시 방법 (부모 노드를 통한 삭제)
const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
parent.removeChild(child);
- 요소 선택:
- getElementById, querySelector 등으로 단일 요소 선택
 - getElementsByClassName, querySelectorAll 등으로 여러 요소 선택
 - 부모, 자식, 형제 관계를 통한 요소 탐색
 
 - 요소 조작:
- textContent, innerHTML로 내용 변경
 - getAttribute, setAttribute로 속성 조작
 - style 프로퍼티나 classList로 스타일 변경
 - createElement, appendChild 등으로 요소 생성 및 추가
 - remove, removeChild로 요소 삭제
 
 
'Web Development > JavaScript' 카테고리의 다른 글
| 실전 DOM 조작 예제 (0) | 2025.03.30 | 
|---|---|
| 이벤트 처리 (0) | 2025.03.30 | 
| DOM 조작 (0) | 2025.03.30 | 
| 배열 (0) | 2025.03.30 | 
| 객체 (0) | 2025.03.30 |