← 목록

DOM 조작을 위한 주니어 개발자를 위한 10가지 팁 🖱️

작성: 2024년 12월 06일읽기: 약 3분

웹 개발에서 DOM(Document Object Model)을 조작하는 것은 웹 페이지의 동적인 요소를 만들고 제어하는 데 필수적입니다. 여기 주니어 개발자들이 알아두면 좋을 10가지 팁을 소개합니다.

1. getElementById 사용하기

웹 페이지에서 특정 요소를 빠르게 찾고 싶다면 getElementById 메소드를 사용하세요. 이 메소드는 ID를 기반으로 요소를 찾아줍니다.

const element = document.getElementById('myElement');

2. querySelectorquerySelectorAll 활용하기

CSS 선택자를 사용하여 요소를 찾고 싶을 때는 querySelectorquerySelectorAll 메소드를 사용하세요. querySelector는 첫 번째 요소를, querySelectorAll은 모든 요소를 반환합니다.

const firstButton = document.querySelector('.btn');
const allButtons = document.querySelectorAll('.btn');

3. 요소에 이벤트 리스너 추가하기

사용자의 동작에 반응하게 하려면 요소에 이벤트 리스너를 추가하세요.

const button = document.querySelector('.btn');
button.addEventListener('click', function() {
  alert('버튼이 클릭되었습니다!');
});

4. classList로 클래스 조작하기

요소의 클래스를 추가, 삭제 또는 토글하고 싶을 때 classList 속성을 사용하세요.

const element = document.querySelector('.myElement');
element.classList.add('new-class');
element.classList.remove('old-class');
element.classList.toggle('active');

5. innerHTMLtextContent로 내용 변경하기

요소의 내용을 변경하고 싶을 때는 innerHTML 또는 textContent 속성을 활용하세요.

const element = document.querySelector('.myElement');
element.textContent = '새로운 텍스트';
element.innerHTML = '<span>새로운 HTML</span>';

6. setAttributegetAttribute로 속성 조작하기

요소의 속성을 조작하고 싶다면 setAttributegetAttribute 메소드를 사용하세요.

const input = document.querySelector('.myInput');
input.setAttribute('type', 'password');
const type = input.getAttribute('type');

7. 스타일 직접 조작하기

요소의 스타일을 JavaScript로 직접 조작하고 싶다면 style 속성을 사용하세요.

const element = document.querySelector('.myElement');
element.style.backgroundColor = 'blue';
element.style.color = 'white';

8. 요소 생성하고 페이지에 추가하기

새로운 요소를 만들고 싶다면 createElement 메소드를, 페이지에 추가하고 싶다면 appendChild 또는 insertBefore 메소드를 사용하세요.

const newElement = document.createElement('div');
newElement.textContent = '새 요소';
document.body.appendChild(newElement);

9. 요소 삭제하기

페이지에서 요소를 삭제하고 싶다면 removeChild 메소드를 사용하세요.

const element = document.querySelector('.myElement');
element.parentNode.removeChild(element);

10. 이벤트 위임 사용하기

여러 요소에 이벤트 리스너를 추가하는 대신, 상위 요소에서 이벤트를 위임하여 관리할 수 있습니다.

document.body.addEventListener('click', function(event) {
  if (event.target.matches('.btn')) {
    alert('버튼 클릭!');
  }
});

이러한 팁들을 활용하여 웹 페이지를 더욱 동적이고 사용자 친화적으로 만들어보세요. Happy coding!