본문 바로가기
IT/자바스크립트

JavaScript `createElement` 완벽 가이드 DOM 요소 생성의 모든 것

by 불멸남생 2025. 3. 25.

JavaScript에서 동적 콘텐츠를 생성할 때 핵심적인 역할을 하는 createElement 메서드는 웹 애플리케이션의 사용자 경험과 구조를 혁신적으로 향상시킬 수 있는 강력한 도구입니다. 이 글에서는 createElement의 기본 사용법부터 고급 활용 사례까지 상세하고 실무적인 정보만을 제공하며, 검색 최적화된 콘텐츠를 통해 관련 키워드에서 상위 노출을 노립니다.

JavaScript createElement란 무엇인가?

createElement는 JavaScript의 Document 객체에서 제공하는 메서드로, HTML 요소를 동적으로 생성할 수 있게 합니다. 이 메서드를 사용하면 기존의 정적인 HTML 구조에 얽매이지 않고 사용자 상호작용이나 로직에 따라 새로운 요소를 실시간으로 추가하거나 수정할 수 있습니다.

const newDiv = document.createElement('div');

위 코드는 div 요소를 새롭게 생성하며, 아직 DOM에 삽입된 상태는 아닙니다. DOM에 추가하려면 별도의 조작이 필요합니다.

반응형

createElement의 기본 문법과 사용 예시

const element = document.createElement(tagName);
  • tagName: 문자열 형태로 HTML 태그 이름을 입력합니다. 예: 'div', 'span', 'ul', 'li', 'a' 등.

기본 사용 예

const paragraph = document.createElement('p');
paragraph.textContent = '안녕하세요, 동적으로 생성된 문단입니다.';
document.body.appendChild(paragraph);

위 예시는 p 요소를 생성하고, 텍스트 콘텐츠를 삽입한 후 body에 추가하는 기본적인 흐름을 보여줍니다.

반응형

속성과 클래스 추가하기

createElement로 생성한 요소는 HTML 속성 및 클래스를 동적으로 추가할 수 있습니다. 이는 사용자의 인터랙션에 따라 스타일이나 동작을 제어하는 데 유용합니다.

setAttribute로 속성 추가

const link = document.createElement('a');
link.setAttribute('href', 'https://example.com');
link.textContent = '예제 링크';

classList로 클래스 제어

link.classList.add('btn', 'btn-primary');

id 직접 설정

link.id = 'mainLink';
반응형

자식 요소와 텍스트 노드 추가하기

동적으로 생성된 요소는 다른 요소나 텍스트 노드를 자식으로 가질 수 있습니다. 이를 통해 복잡한 구조를 코드로 정의할 수 있습니다.

텍스트 노드 생성

const textNode = document.createTextNode('텍스트 노드입니다.');
element.appendChild(textNode);

중첩된 요소 생성

const card = document.createElement('div');
card.classList.add('card');

const cardBody = document.createElement('div');
cardBody.classList.add('card-body');

const cardText = document.createElement('p');
cardText.textContent = '카드 안의 텍스트입니다.';

cardBody.appendChild(cardText);
card.appendChild(cardBody);
document.body.appendChild(card);
반응형

createElement와 appendChild 차이점 및 관계

  • createElement는 요소를 생성하는 역할
  • appendChild는 요소를 DOM에 삽입하는 역할

같이 쓰는 예

const li = document.createElement('li');
li.textContent = '리스트 아이템';
document.querySelector('ul').appendChild(li);

이와 같은 조합을 통해 유저 이벤트나 API 응답 등에 따라 리스트나 카드 등의 UI 요소를 동적으로 구성할 수 있습니다.

반응형

createElement와 innerHTML의 차이점

구분 createElement innerHTML

성능 빠름 느림
보안 안전 XSS 취약
제어 요소 단위 문자열 기반
유연성 높음 제한적

보안과 구조적인 유연성을 고려하면 createElement가 우수한 선택입니다. 특히 이벤트 리스너 부착, 애니메이션 조작 등 DOM 제어가 필요한 상황에 최적화되어 있습니다.

반응형

실무에서 자주 사용하는 패턴

1. 반복문을 통한 리스트 생성

const fruits = ['사과', '바나나', '딸기'];
const ul = document.createElement('ul');

fruits.forEach(fruit => {
  const li = document.createElement('li');
  li.textContent = fruit;
  ul.appendChild(li);
});

document.body.appendChild(ul);

2. 폼 요소 동적 생성

const form = document.createElement('form');
form.setAttribute('method', 'POST');

const input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'username');

const button = document.createElement('button');
button.textContent = '제출';

form.appendChild(input);
form.appendChild(button);

document.body.appendChild(form);
반응형

이벤트 리스너와의 결합

createElement로 생성한 요소는 addEventListener를 통해 이벤트를 부여할 수 있습니다.

const btn = document.createElement('button');
btn.textContent = '클릭하세요';

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

document.body.appendChild(btn);

동적으로 생성한 요소에 리스너를 즉시 연결해야 이벤트가 작동하는 점에 유의하세요.

반응형

createElement를 활용한 컴포넌트 구조 설계

모듈화된 컴포넌트를 작성할 때도 유용합니다.

예: 카드 컴포넌트 함수화

function createCard(title, content) {
  const card = document.createElement('div');
  card.classList.add('card');

  const h3 = document.createElement('h3');
  h3.textContent = title;

  const p = document.createElement('p');
  p.textContent = content;

  card.appendChild(h3);
  card.appendChild(p);

  return card;
}

document.body.appendChild(createCard('제목', '본문 내용입니다.'));

이 구조는 React 등 현대 프레임워크의 컴포넌트 패턴과 유사하여 이식성이 높습니다.

반응형

사용자 정의 속성(data-attribute) 설정

데이터 전달 및 추적 목적으로 data-* 속성을 활용할 수 있습니다.

const button = document.createElement('button');
button.textContent = '삭제';
button.setAttribute('data-id', '123');

이후 이벤트 핸들러에서 해당 속성을 참조할 수 있습니다:

button.addEventListener('click', (e) => {
  const id = e.target.getAttribute('data-id');
  console.log(`ID ${id}의 항목 삭제`);
});
반응형

템플릿 사용 없이 순수 JS만으로 구조 설계하기

템플릿 엔진 없이도 createElement와 함수 구조만으로도 상당히 복잡한 UI를 구축할 수 있습니다.

다중 중첩 구조 예시

function createTodoItem(text) {
  const li = document.createElement('li');
  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';

  const span = document.createElement('span');
  span.textContent = text;

  li.appendChild(checkbox);
  li.appendChild(span);
  return li;
}

const ul = document.createElement('ul');
ul.appendChild(createTodoItem('할 일 1'));
ul.appendChild(createTodoItem('할 일 2'));

document.body.appendChild(ul);
반응형

결론

  • 동적 요소 생성
  • 속성 및 이벤트 처리
  • DOM 구성 제어
  • XSS 방지 등 보안적 이점

createElement는 단순한 HTML 생성 도구가 아니라, 동적이고 반응형 웹 애플리케이션을 구현하는 데 있어 핵심적인 역할을 합니다. JavaScript 기반의 모던 웹 개발에서 반드시 숙지해야 할 필수 기술입니다.

반응형