세션을 진행하며 todoList, 로그인을 구현해 보았다. 이 과정에서 배운 것을 정리해보려 한다.
HTML 문서가 로드된 후에 자바스크립트 코드를 실행할 수 있게 하기
document.addEventListener('DOMContentLoaded', callback);
를 사용하면, HTML 문서의 모든 요소(이미지, stylesheet, JavaScript파일 등)가 로드되었을 때 callback 함수가 실행된다. 일반적으로 로직, 함수가 어디서 시작하고 어떤 흐름으로 흘러가는지 알기 위해 init 함수를 만들고 callback함수로 init함수를 놓는다.
HTML 요소 가져오기
동적인 일을 하려면 HTML 요소를 가져와 다뤄야 한다,
다음과 같은 방법으로 HTML에 있는 요소를 가져올 수 있다. 자주 사용한 방법만 나열하도록 하겠다.
1. document.getElementById: 해당 id 속성을 가진 요소를 가져온다.
const element = document.getElementById('Id');
2. document.querySelector: CSS 선택자를 이용하여 요소를 가져온다.
const element = document.querySelector('#id');
const element2 = document.querySelector('.class');
HTML 요소 생성, 수정, 삽입하기
HTML 요소는 다음과 같이 생성할 수 있다.
const divEl = document.createElement("div");//div 태그 생성
HTML 요소는 다음과 같이 수정할 수 있다.
1. innerHTML 속성을 이용하여 HTML 내용을 수정할 수 있다.
const element = document.querySelector('#Id');
element.innerHTML = '<p>Hello World</p>';
2. textContent 속성을 이용하여 텍스트 내용을 수정할 수 있다.
const element = document.querySelector('#Id');
element.textContent = 'Hello world';
3. setAttribute 메소드를 이용하여 속성 값을 수정할 수 있다.
const element = document.querySelector('#Id');
element.setAttribute('class', 'newClass');
4. input, select, textarea 태그에서 value 속성을 사용하여 값을 가져오고 수정할 수 있다.
const element = document.querySelector('#Id');
const inputText = element.value;
HTML 요소는 다음과 같이 삽입할 수 있다.
1. appendChild 메소드를 이용하여 자식 요소를 추가할 수 있다.
const element = document.querySelector('#Id');
const child = document.createElement('p');
element.appendChild(child);
2. removeChild 메소드를 이용하여 자식 요소를 제거할 수 있다.
const element = document.querySelector('#Id');
const child = element.querySelector('p');
element.removeChild(child);
다른 HTML 문서로 이동하기
동적인 기능을 사용하다 보면 다른 HTML 문서로 이동해야 하는 경우가 생길 수 있다. location.href를 사용하면 다른 HTML 문서로 이동할 수 있다.
location.href = './next.html';
'JavaScript' 카테고리의 다른 글
JavaScript 런타임과 V8 엔진, 비동기 처리 원리 (1) | 2023.04.14 |
---|---|
(JavaScript)localStorage, JSON (0) | 2023.04.09 |
(JavaScript)forEach, map, filter (0) | 2023.04.08 |
(JavaScript)개념 정리 (1) | 2023.04.01 |