- Manipulating Elements, 요소 조종하기
자바스크립트의 기본적인 목적은 웹사이트에 동적인 움직임을 주기 위함이다. 그러므로 요소를 선택해서 변화시킬 수 있어야 한다. 앞에서 요소를 선택하기 위한 방법으로 querySelector, querySelectorAll, getElementById, get ElementsByClassName, getElementsByTagName을 썼었다.(get을 쓸 때 id를 제외하곤 Element에 s가 붙는다)
이번에는 선택된 요소에 class를 추가하거나 제거하고, text는 어떻게 추가하는지 등등, 요소를 조종하는 방법을 알아보겠다.
class를 조종하는 방법에는 기본적으로 add, remove, toggle가 있다.
- add : class에 원하는 class name을 추가한다.
- remove : class에 원하는 class name을 제거한다.
- toggle : class에 원하는 class name이 없다면 추가하고, 원하는 class name이 이미 존재한다면 제거한다. 그리고 전자의 경우에는 true를 출력하고, 후자의 경우에는 false를 출력한다.
요소 자체를 추가하고 제거하는 방법은 다음과 같다.
- createElement : 요소를 생성할 수 있다.
- setAttribute : 요소에 속성과 그 속성의 값을 부여할 수 있다.
- appendChild : 해당 태그의 맨 끝에 요소를 추가한다.
- textContent : 요소의 text를 제어할 수 있다.
- style : CSS 요소를 제어할 수 있다.
Quiz
아래 두가지 예제 코드의 차이점을 분별하시오.
1.
const something = document.createElement("p");
for (let i = 0; i < 5; i++) {
something.textContent = i;
document.body.appendChild(something);
}
2.
for (let i = 0; i < 5; i++) {
const something = document.createElement("p");
something.textContent = i;
document.body.appendChild(something);
}
전자의 경우, something이 1번 선언된다. i가 0에서 4까지 5번 반복할 때마다 append는 되지만 반복될 때마다 추가되는 것이 아니라 text가 바뀔 뿐이다. 풀어 쓰면 다음과 같다.
const something = document.createElement('p');
something.textContent = 0;
document.body.appendChild(something);
something.textContent = 1;
document.body.appendChild(something);
something.textContent = 2;
document.body.appendChild(something);
something.textContent = 3;
document.body.appendChild(something);
something.textContent = 4;
document.body.appendChild(something);
something은 1번 선언되었기 때문에 하나의 something만 추가된다. 처음에는 0이 추가되었겠지만, 0이 1로 바뀌고 2로 바뀌고 3으로 바뀌고 4로 바뀌는 것이다. 웹에는 4만 출력된다.
이와 다르게 후자의 경우는 something이 5번 선언된다. 그리고 중요한 것은, for문 안에서 선언된 변수는 1번 끝날 때마다 사라지고 다시 새로운 메모리를 할당 받는다. 따라서 i가 0에서 4까지 5번 반복할 동안 새로운 something이 선언된다. 풀어 쓰면 다음과 같다.
const something = document.createElement('p');
something.textContent = '0';
document.body.appendChild(something);
const something = document.createElement('p'); // 기존 something은 사라지고 새로운 something
something.textContent = '1';
document.body.appendChild(something);
const something = document.createElement('p'); // 기존 something은 사라지고 새로운 something
something.textContent = '2';
document.body.appendChild(something);
const something = document.createElement('p'); // 기존 something은 사라지고 새로운 something
something.textContent = '3';
document.body.appendChild(something);
const something = document.createElement('p'); // 기존 something은 사라지고 새로운 something
something.textContent = '4';
document.body.appendChild(something);
something이 선언될 때마다 text가 바뀌고 body에 추가된다. 웹에는 0부터 4까지의 숫자가 출력된다.
'프로그래밍 > 바닐라코딩_Prep Guide' 카테고리의 다른 글
Step 4. Interacting with Webpages(4) (0) | 2021.12.21 |
---|---|
Step 4. Interacting with Webpages(3) (0) | 2021.12.16 |
Step 4. Interacting with Webpages(1) (0) | 2021.12.13 |
Step 3. Algorithm (0) | 2021.11.30 |
Step 2. JavaScript(9) - Object, 객체 (0) | 2021.11.29 |