요소 노드 생성

자바스크립트에서는 DOM API를 사용해 요소 노드들을 추가하고 조작할 수 있습니다.
먼저, DOM API를 사용해 요소 노드를 추가해보겠습니다.

createElement

자바스크립트에서는 createElement 메서드를 통해 새로운 요소 노드를 생성할 수 있습니다.
createElement 메서드를 사용해 class 이름이 season이고, div로 이루어진 요소를 추가해보겠습니다.

const seasonElement = document.createElement("div");

이 createElement의 매개변수로는, 생성할 요소의 태그 이름을 넣어줍니다.

이렇게 createElement로 요소 노드를 생성한 다음, classList를 사용해 season 이라는 class 이름을 설정해주겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

이렇게 원하는 요소를 생성해보았으니, 이번엔 이 요소의 안에 텍스트를 넣어보도록 하겠습니다.
이렇게 새로 생성한 요소에 안에 텍스트를 넣는 방법은 두 가지가 있습니다.

그 중 하나는 이전에 우리가 배웠던 textContent를 사용하는 것입니다.
textContent를 사용해 "spring"이라는 텍스트를 넣어보겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

seasonElement.textContent = "spring";

이렇게 텍스트를 추가하는 또 다른 방법은, 텍스트 노드를 생성하는 createTextNode라는 메서드를 사용하는 것 입니다.
createTextNdoe 메서드도 매개변수로 원하는 텍스트를 전달받습니다. 한 번 사용해보겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

//seasonElement.textContent = "spring";
const seasonText = document.createTextNode("spring");

여기까지 작성을 한 다음에 태그 이름이 div인 모든 요소들을 getElementsByTagName을 사용해 출력해보도록 하겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

//seasonElement.textContent = "spring";
const seasonText = document.createTextNode("spring");
console.log(document.getElementsByTagName("div"));

코드를 실행해보면, 우리가 생성한 요소가 출력되지 않는 것을 볼 수 있습니다.

분명히 직접 DOM에 요소들을 추가해보는 메서드라고 했는데 왜 출력이 되지 않는 것일까요?

그 이유는 이렇게 생성한 요소와 텍스트 노드들은 생성만 되었을 뿐, 아직 DOM Tree에 추가 된 것이 아니기 때문입니다.

이렇게 생성한 요소 노드, 텍스트 노드들은 appendChild를 사용해 DOM Tree에 추가할 수 있습니다.

appendChild

appendChild 메서드는 매개변수로 전달받은 노드를 특정 요소의 마지막 자식으로 추가하는 메서드입니다.

이 DOM Tree는 상하 관계를 한 눈에 볼 수 있는 트리 구조라고 했었는데요, 이 상하 관계는 보통 서로 부모와 자식 관계라고 부릅니다.

우리는 현재 DOM Tree에서 class 이름이 date인 요소와 clock인 요소의 위쪽에 위치하고있는 요소노드, 즉 이들의 부모 요소인 today-info 라는 이름의 class를 가진 요소에 appendChild를 사용해 이 today-info 요소의 자식 요소로 seasonElement를 추가해보도록 하겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

//seasonElement.textContent = "spring";
const seasonText = document.createTextNode("spring");
const todayInfoElement = document.querySelector("div.today-info");
todayInfoElement.appendChild(seasonElement);

console.log(document.getElementsByTagName("div"));

그 다음, 여기서 생성한 seasonText 라는 텍스트 노드는, seasonElement 요소의 내부에 들어가야 하는 텍스트이기 때문에 seasonElement의 자식 노드로 들어가야하므로, 동일하게 seasonElement에 appendChild를 사용해 seasonElement의 자식 노드로 넣어주도록 하겠습니다.

const seasonElement = document.createElement("div");
seasonElement.classList.add("season");

//seasonElement.textContent = "spring";
const seasonText = document.createTextNode("spring");
const todayInfoElement = document.querySelector("div.today-info");
todayInfoElement.appendChild(seasonElement);
seasonElement.appendChild(seasonText);

console.log(document.getElementsByTagName("div"));

코드를 실행하면, 이번에는 가장 아래쪽에 우리가 추가한

<div class="season">spring</div>

이라는 값이 출력되는 것을 볼 수 있습니다.

이렇게 자바스크립트에서는 직접 DOM Tree에 요소 노드와 텍스트 노드를 추가할 수 있습니다.

그럼 이번에는 지금까지 작성했던 코드를 전부 지우고, 배운 내용들을 사용해 동일하게 class 이름이 clock인 요소의 아래에 class이름이 button이고, "버튼" 이라는 텍스트가 적혀있는 div를 추가해보겠습니다.

const buttonElement = document.createElement("div");
buttonElement.classList.add("button");
buttonElement.textContent = "버튼";
const todayInfoElement = document.querySelector("div.today-info");
todayInfoElement.appendChild(buttonElement);

console.log(document.getElementsByTagName("div"));

여기까지 작성해보셨다면, 이제 DOM API를 사용해 웹 요소들을 조작하는 방법에 대해 완벽하게 이해하신 것이기 때문에, 다음 단계로 넘어가보도록 하겠습니다.

addEventListener

이번에는 이 버튼이 정말 버튼처럼 동작하게, 즉 버튼을 클릭하면 어떠한 작업이 실행되게 만들어보겠습니다.

DOM은 특정 요소들에 이벤트를 추가할 수 있는 addEventListener 라는 DOM API를 제공합니다.

우리는 직접 추가한 buttonElement에 이벤트를 추가해야하므로, buttonElement에 addEventListener를 작성해보겠습니다.

addEventListener를 작성하면, 이렇게 많은 이벤트 종류들이 나오게됩니다.

우리는 버튼을 클릭 해야하므로, "click" 이라는 이벤트를 사용해보겠습니다.

이 addEventListener는 이벤트의 종류 말고도 또 다른 매개변수를 받는데요, listener 라는 매개변수로, 앞에 작성한 이벤트가 행해졌을 때, 실행될 함수를 전달받습니다.

자바스크립트의 window라는 객체의 alert라는 메서드를 사용해 버튼을 클릭하면, 경고창을 띄우는 함수를 매개변수로 전달해주겠습니다.

const buttonElement = document.createElement("div");
buttonElement.classList.add("button");
buttonElement.textContent = "버튼";
const todayInfoElement = document.querySelector("div.today-info");
todayInfoElement.appendChild(buttonElement);
buttonElement.addEventListener("click", () => {
  window.alert("클릭");
});

console.log(document.getElementsByTagName("div"));

지금 작성한 window 객체는 현재 사용하고 있는 웹 브라우저의 창을 나타내는 객체로, 경고창을 띄우는 alert, 확인과 취소의 버튼이 있는 confirm과 같은 다양한 메서드들을 포함하고 있습니다.

작성한 코드를 실행한 다음, 브라우저 탭에 들어가서 버튼 이라는 글자를 눌러보면, "클릭" 이라는 단어가 적혀있는 경고창이 실행되는 것을 볼 수 있습니다.

특정 요소에 이벤트를 추가 하고, 수행할 함수를 지정할 수 있는 이 addEventListener 에는 click 과 같이 스크롤을 하면 이벤트를 발생시키는 scroll, 마우스를 특정 요소의 위에 올리면 이벤트가 발생하는 mouseover 등 정말 많은 이벤트 종류들이 있습니다.

이 이벤트들을 전부 다 알고있어야 한다기 보다는, 자주 사용되는 이벤트들을 위주로, 이벤트 리스너를 사용 할 때마다 검색해보면서 사용해보시는 것을 추천드립니다.

지금 이 브라우저 탭을 보면, "버튼" 이라는 글자가 적힌 버튼이, 위에 있는 02.10.금요일, 15:03과 같이 정말 텍스트인 것 처럼 표시되어있습니다.

우리는 이 buttonElement가 정말 버튼처럼 동작하라고 이벤트까지 추가를 해주었는데, 버튼의 스타일이 그냥 텍스트 처럼 보이는 스타일이라면, buttonElement를 실제 버튼으로 사용하기 어려울 것 같습니다.

그럼 이제는 이 buttonElement를 실제 버튼 모양처럼 만들어주도록 하겠습니다.

style

DOM API에는 특정 요소의 스타일을 추가하고 수정하는 API도 있습니다.
이번에는 style이라는 프로퍼티를 사용해 이 buttonElement에 스타일을 추가해보겠습니다.

const buttonElement = document.createElement("div");
buttonElement.classList.add("button");
buttonElement.textContent = "버튼";
buttonElement.style.color = "white";
buttonElement.style.backgroundColor = "gray";
buttonElement.style.width = "50px";
buttonElement.style.textAlign = "center";
buttonElement.style.cursor = "pointer";

const todayInfoElement = document.querySelector("div.today-info");
todayInfoElement.appendChild(buttonElement);
buttonElement.addEventListener("click", () => {
  window.alert("클릭");
});

console.log(document.getElementsByTagName("div"));

style 프로퍼티를 사용하면, 특정 요소에 이렇게 다양한 스타일을 적용할 수 있습니다.

코드를 실행해보면, 실제로 위에 작성된 텍스트와는 구분되게 정말 버튼처럼 스타일이 수정된 것을 볼 수 있습니다.

이렇게 자바스크립트에서는 여러가지 DOM API를 사용하면, 요소 노드와 텍스트 노드들을 추가할 수 있고, 스타일과 이벤트 까지 추가할 수 있습니다.


본 내용은 웹 프론트엔드를 위한 자바스크립트 첫 걸음 강의 내용의 일부입니다.
velog 사용자 분들을 위해 25% 할인 쿠폰을 제공해드립니다😊

쿠폰 번호 : 11343-714bb0d01b59
쿠폰 사용 기간 : 7월 15일까지

0개의 댓글