Dom과 이벤트
DOM과 이벤트
1️⃣DOM이란?
DOM(Document Object Model)은 HTML 문서를 자바스크립트로 다룰 수 있게 만든 구조. HTML을 트리처럼 표현하고, 각 요소를 노드라는 단위로 관리한다.
2️⃣요소 다루기
요소 선택
- getElementById : id로 선택
- querySelector : CSS 요소 선택(일치하는 첫번째 요소)
- querySelectorAll : CSS 요소 선택(일치하는 요소 전부, 배열로 반환)
document.getElementById("id"); document.querySelector(".text"); document.querySelectorAll(".text"); // querySelector 괄호안에는 '.text', '#id', 'footer' 등 다 들어갈 수 있음
선택한 요소 내부 변경
- textContent
- innerHTML ```javascript
안녕!
### 요소 속성 변경
- setAttribute("속성", "값")
```javascript
<img id="pic" src="./img1" alt="이미지">
<script>
const pic = document.getElementById("pic");
pic.setAttribute("alt", "hi"); // <img id="pic" src="./img1" alt="hi">
</script>
요소 스타일 변경
- style.스타일속성 = “값”
- style.cssText = “css 코드” : 여러개 한번에 변경 가능
box.style.width = '300px'; box.style.background = 'lightcoral'; box.style.cssText = 'width:300px; background: lightcoral;';
요소 클래스 변경
- classList.add(“클래스명”) : 클래스 추가
- classList.remove : 클래스 제거
- classList.toggle : 클래스 껐다켰다(ex. 버튼이벤트로 스타일 on/off)
- classList.contains : 해당 클래스를 포함하면 true, 아니면 false
btn.classList.add("highlight"); btn.classList.remove("shadow"); btn.classList.toggle("rotate"); btn.classList.contains("active");
3️⃣이벤트란?
사용자의 행동(클릭, 입력, 키보드 등)에 반응해서 코드가 실행되는 것. 자바스크립트로 이벤트를 감지해서 원하는 작업을 실행한다.
이벤트 등록방법
- 인라인
- 이벤트 리스너
다 못썻음 나중에 마저 쓸게요…ㅎ