1. DOMContentLoaded 이벤트
해당 이벤트는 웹 브라우저가 문서 객체를 모두 읽고 나서 실행하는 이벤트
2. 문서 객체 가져오기
document.head
document.body
document.title
document.querySelector(선택자)
document.querySelectorAll(선택자)
3. 글자 조작하기
4. 속성 조작하기
5. 스타일 조작하기
h1.style.backgroundColor // 해당 방법을 많이 사용
h1.style['backgroundColor']
h1.style['background-color']
6. 문서 객체 생성하기
document.createElement(문서 객체 이름)
부모 객체.appendChild(자식 객체)
7. 문서 객체 이동하기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>외부 스타일 시트</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const divA = document.querySelector('#first')
const divB = document.querySelector('#second')
const h1 = document.createElement('h1')
h1.textContent = '이동하는 h1 태그'
const toFirst = () => {
divA.appendChild(h1)
setTimeout(toSecond, 1000)
}
const toSecond = () => {
divB.appendChild(h1)
setTimeout(toFirst, 10000)
}
toFirst()
})
</script>
<body>
<div id="first">
<h1>첫 번째 div 태그 내부</h1>
</div>
<hr>
<div id = "second">
<h1>두 번째 h1 태그 내부</h1>
</div>
</body>
</body>
</html>
8. 문서 객체 제거하기
부모 객체.removeChild(자식 객체)
문서 객체.parentNode.removeChild(문서 객체)
9. 이벤트 설정하기
문서 객체.addEventListener(이벤트 이름, 콜백 함수)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>외부 스타일 시트</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
let counter = 0
const h1 = document.querySelector('h1')
h1.addEventListener('click', (event) => {
counter ++
h1.textContent = `클릭 횟수: ${counter}`
})
})
</script>
<style>
h1 {
user-select : none;
}
</style>
<body>
<h1> 클릭 횟수 : 0 </h1>
</body>
</body>
</html>
문서 객체.removeEventListener(이벤트 이름, 이벤트 리스너)
1. 이벤트 모델
2. 키보드 이벤트
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>외부 스타일 시트</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const textarea = document.querySelector('textarea')
const h1 = document.querySelector('h1')
textarea.addEventListener('keyup', (event) => {
const length = textarea.value.length
h1.textContent = `글자 수 : ${length}`
})
})
</script>
<body>
<h1></h1>
<textarea></textarea>
</body>
</body>
</html>
3. 글자 입력 양식 이벤트
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>외부 스타일 시트</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input')
const button = document.querySelector('button')
const p = document.querySelector('p')
button.addEventListener('click', () => {
const inch = Number(input.value)
if (isNaN(inch)) {
p.textContent = '숫자를 입력해주세요'
return // 조기 리턴
}
const cm = inch * 2.54
p.textContent = `${cm} cm`
})
})
</script>
<body>
<input type = "text"> inch<br>
<button>계산</button>
<p></p>
</body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>외부 스타일 시트</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select')
const p = document.querySelector('p')
select.addEventListener('chancge', (event) => {
const options = event.currentTarget.options
const index = event.currentTarget.options.selectedIndex
p.textContent = `선택 : ${options[index].textContent}`
})
})
</script>
<body>
<select>
<option>떡볶이</option>
<option>순대</option>
<option>오뎅</option>
<option>튀김</option>
</select>
<p>선택 : 떡볶이</p>
</body>
</body>
</html>
4. 기본 이벤트 막기
기본 과제
p.315 출력되는 고양이 이미지 캡쳐
[코드]
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>기본 과제</title>
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const rects = document.querySelectorAll('.rect'); // querySelectorAll로 수정
rects.forEach((rect, index) => {
const width = (index + 1) * 100;
const src = `https://placekitten.com/${width}/250`; // URL 수정 (http → https)
rect.setAttribute('src', src);
});
});
</script>
<img class="rect">
<img class="rect">
<img class="rect">
<img class="rect">
<img class="rect">
</body>
</html>
[결과]
추가 과제
p.352의 할 일 목록 만들기
[코드]
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>할 일 목록</title>
</head>
<body>
<h1>할 일 목록</h1>
<input id="todo">
<button id="add-button">추가하기</button>
<div id="todo-list"></div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('#todo');
const todoList = document.querySelector('#todo-list'); // 수정됨
const addButton = document.querySelector('#add-button');
let keyCount = 0;
const addTodo = () => {
if (input.value.trim() === '') {
alert('할 일을 입력해주세요.');
return;
}
const item = document.createElement('div');
const checkbox = document.createElement('input');
const text = document.createElement('span');
const button = document.createElement('button');
const key = keyCount;
keyCount += 1;
item.setAttribute('data-key', key);
item.appendChild(checkbox);
item.appendChild(text);
item.appendChild(button);
todoList.appendChild(item);
checkbox.type = 'checkbox';
checkbox.addEventListener('change', (event) => {
item.style.textDecoration = event.target.checked ? 'line-through' : '';
});
text.textContent = input.value;
button.textContent = '제거하기';
button.addEventListener('click', () => { // 수정됨
removeTodo(key);
});
input.value = '';
};
const removeTodo = (key) => { // 수정됨
const item = document.querySelector(`[data-key="${key}"]`); // 수정됨
if (item) {
todoList.removeChild(item); // 수정됨
}
};
addButton.addEventListener('click', addTodo);
input.addEventListener('keyup', (event) => {
if (event.key === 'Enter') { // 최신 문법으로 수정됨
addTodo();
}
});
});
</script>
</body>
</html>
[결과]