자바스크립트 Element 객체 가져오기 getElementById, getElementsByClassName, querySelector

반응형

자바스크립트에서 DOM 엘리먼트 객체를 구할 수 있는 방법 4가지를 소개해드리겠습니다. 

getElementById("id")

 ID 값을 통하여 자바스립트 객체를 가지고 올 수 있습니다.

<ul>
    <li id = "red">Red</li>
    <li id = "blue">Blue</li>
</ul>
const red = document.getElementById("red");
const blue = document.getElementById("blue");

red.style.color = "red";
blue.style.color = "blue";

결과

getElementById 를 통하여 ID값을 호출하여서 CSS에서 폰트 색깔을 주었습니다.

  • Red
  • Blue
 

getElementsByClassName("className")

class 이름을 가진 모든 객체가 담긴 배열을 가져옵니다.

<ul>
  <li class = "superman hero">Superman</li> 
  <li class = "batman hero">Batban</li>
  <li class = "pororo hero">pororo</li>
</ul>

li에 태그에 hero라는 클래스를 부여하였습니다.

const hero = document.getElementsByClassName("hero");
  
for(var i = 0; i<hero.length; i++){
  hero[i].style.fontSize = "xx-large"; 
}

결과

  • Superman
  • Batban
  • pororo

두 가지의 클래스를 가지고 있는 객체를 찾고 싶은 경우

superman 그리고 hero 클래스 두 가지를 모두 갖는 경우를 찾습니다.

const hero = document.getElementsByClassName("superman hero")

querySelector와 querySelectorAll

  • querySelector : 가장 먼저 찾아진 하나의 메서드만 반환
  • querySelectorAll : 문서 내에 있는 조건에 맞는 모든 객체
const x = document.querySelector(".hero");
const y = document.querySelectorAll("#superman");

파라미터: selector

  • #아이디 : 엘리먼트 태그 값 중 id 속성으로 검색
  • 클래스 : 엘리먼트 태그 값 중 class 속성으로 검색
728x90
반응형