CSS HTML JS

[JS] 자바스크립트 DOM 요소 선택 정리

ziziDev 2025. 6. 16. 21:08
반응형

✅ 자바스크립트 DOM 요소 선택 정리

DOM(Document Object Model)에서 HTML 요소를 자바스크립트로 선택할 수 있는 여러 가지 방법이 있습니다. 아래는 가장 자주 사용하는 선택자들에 대한 설명과 차이점


🔹 getElementById

  • id 속성값으로 요소를 선택
  • 항상 하나의 요소만 반환 (단일)
 
const title = document.getElementById("myTitle");

🔹 getElementsByClassName

  • class 속성값으로 요소를 선택
  • 🔁 여러 요소를 선택할 수 있으며, HTMLCollection을 반환 (유사 배열)
 
const items = document.getElementsByClassName("menu-item"); items[0].innerText = "첫 번째 메뉴";

🔹 getElementsByTagName

  • ✅ <div>, <h1>, <p> 등 태그명으로 요소를 선택
  • 🔁 여러 요소를 선택할 수 있으며, HTMLCollection 반환
 
const headers = document.getElementsByTagName("h1"); console.log(headers.length); // h1 태그 몇 개?

🔹 querySelector

  • CSS 선택자 방식으로 요소를 선택 (.class, #id, tag, 조합 가능)
  • 🔹 가장 처음 발견되는 하나의 요소만 반환 (단일)
 
const firstItem = document.querySelector(".menu li");

🔹 querySelectorAll

  • ✅ CSS 선택자 방식으로 모든 일치하는 요소를 NodeList로 반환
  • 🔁 반복문 (forEach) 사용 가능
 
const allItems = document.querySelectorAll(".menu li"); allItems.forEach(item => { item.style.color = "blue"; });

✍️ 요약 비교표

선택자방식반환 형태여러 개 선택 가능?반복 가능?
getElementById id 단일 요소
getElementsByClassName class HTMLCollection 🔁 (for, spread 등)
getElementsByTagName 태그 HTMLCollection 🔁
querySelector CSS 선택자 단일 요소
querySelectorAll CSS 선택자 NodeList ✅ (forEach)
 

✅ 추천 사용 방식

🔥 앞으로는 querySelector / querySelectorAll을 사용하는 것이 가장 직관적이고 유연
CSS 선택자 문법을 그대로 사용할 수 있어 매우 편리해요!

 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Practive App</title>
</head>
<body>
    <h1 autofocus class="hello" id="title">hello!</h1> <!-- id 는 한번만 사용해야함 class 경우 여러번 쓸 수 없음  그래서 아래있는 id는 무시될 수 있음-->
    <h1 id="title">me too!</h1> <!-- 이건 코드로 불러와도 수정이 되지 않는다-->
    <h1 class="hello">me too!</h1>
    <h1 class="hello">me too!</h1>
    <h1 class="hello">me too!</h1>
    <script src="app.js"></script>
</body>
</html>

 

//hello 안에 있는 h1을 가지고 오자
const exam = document.querySelector(".hello h1"); //.menu → class="menu"

const example = document.querySelector("#title"); //#hello → id="hello"

 

 

✅ 정리:

구분CSS 선택자예시설명
Class . (점) .box class="box"인 요소 선택
ID # (샵) #main id="main"인 요소 선택
반응형