FE/JavaScript

[JS] DOM이란? / DOM 요소 다루기

셰욘 2024. 12. 17. 10:58
728x90

DOM이란?

Document Object Model

  • HTML 문서를 브라우저에서 JavaScript로 접근하고 조작할 수 있도록 트리 구조로 표현한 것
  • DOM을 활용하면 HTML 요소를 선택하고, 내용을 변경하거나 스타일을 변경할 수 있다.

DOM 요소찾기

getElement-* 함수 사용

// 아이디로 찾기
let getTagById = document.getElementById("subtitle");

// 태그 이름으로 찾기
let getTagByTagName = document.getElementsByTagName("h1");

// 클래스로 찾기
let getTagByClassName = document.getElementsByClassName("title");

 

querySelector, querySelectorAll 함수 사용

// 해당되는 태그 하나만 찾기
let getTagSelector = document.querySelector(".title");
let getTagSelectorId = document.querySelector("#subtitle");

// 해당되는 태그 여러 개 찾기
let getTagSelectorAll = document.querySelectorAll(".title");

DOM 요소 변경

<body>
    <h1 id="title">제목</h1>
    <img src="image.jpg" id="img">
</body>
let getTagById = document.getElementById("title");

// html 내용 변경
getTagById.innerHTML = "변경";

// 이미지 변경
let getImg = document.querySelector("#img");
getImg.src = "test.png"

// css 스타일 변경
getTagById.style.backgroundColor = "blue";

 


DOM에서 이벤트 추가하기

DOM 요소에 함수 연결하기

<div class="container">
    <img src="images/cat.jpg" id="cat">
</div>

<script>
    let cat = document.querySelector("#cat");
    cat.onclick = () => alert("이미지를 클릭했습니다");
</script>

 

addEventListener

  • 이벤트: 이벤트 유형 지정(click, keypress 등)
  • 함수: 이벤트가 발생하면 실행할 명령이나 함수
  • 캡처 여부: 이벤트를 캡처하는지 여부. true면 캡처링, false면 버블링 (기본값 false)
요소.addEventListener(이벤트, 함수, 캡처 여부);
<div class="container">
    <img src="images/cat.jpg" id="cat">
</div>

<script>
    let cat = document.querySelector("#cat");
    // 함수 연결하기
    cat.addEventListener('mouseover', changePic, false);
    
    function changePic() {
    	cat.src = "images/kitty-1.png";
    }
    
    // 이벤트 리스너 안에서 함수 선언하기
    cat.addEventListener('click', () => {
    	cat.src = "images/kitty-2.png";
    });
</script>

 

const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
	console.log("button click!");
});


DOM에서 노드 추가, 삭제

<body>
	<h1>제목</h1>
</body
let bodyTag = document.querySelector("body");

// 노드 추가하기
const newH1Tag = document.createElement("h1");
newH1Tag.innerHTML = "새로운 h1";
bodyTag.appendChild(newH1Tag);

// 노드 삭제하기
const rmTag = document.querySelector("h1");
rmImg.remove()

 

 


속성 추가, 속성값 가져오기

// 속성 추가
변수이름.setAttribute("속성 이름", 값);

// 속성의 값 가져오기
변수이름.getAttribute("속성이름");

스타일 클래스 추가, 삭제

// 클래스 추가
요소.classList.add("클래스명");

// 클래스 삭제
요소.classList.remove("클래스명");

 

<head>
    <style>
        .color_red {
            color: red;
        }
    </style>
</head>

<body>
    <h1>제목</h1>
    <h1>제목</h1>
    <h1>제목</h1>
</body>
// h1 태그들 중 첫 번째 h1만 color_red 클래스 추가
document.querySelectorAll("h1")[0].classList.add("color_red");

// 클래스 삭제
document.querySelectorAll("h1")[0].classList.remove("color_red");

 

728x90