html 요소 검색-querySelector, classList 등

Wonju·2021년 12월 6일
0

querySelector

getElementById, getElementByClassname 말고,

querySelector 는 HTML 요소를 CSS와 같은 방식으로 검색할 수 있다.

<div class="hello">
  <h1>Pepsi</h1>
</div>

querySelector를 사용한다면 'hello' 라는 클래스 내부의 <h1>태그를 가져올 수 있다는 것.

const abc = document.querySelector(".hello h1");
console.log(abc);
	// <h1>Pepsi</h1>

굿.
물론 id요소를 찾고싶다면 querySelector("#샬라샬라") 하면 된다.


하지만 .hello 안에 h1 이 있는게 저 하나말고 여러개일수도 있지 않을까?

<div class="hello">
  <h1>Pepsi</h1>
</div>
<div class="hello">
  <h1>Dr.Pepper</h1>
</div>
<div class="hello">
  <h1>Sprite</h1>
</div>

위의 querySelector 코드를 그대로 쓴다면 3개가 다 출력될까?
결과는
맨 위의 코드 (Pepsi)만 출력된다.

querySelector는 맨 첫번째 요소만 가져온다.


여러개를 가져오고 싶다면?

querySelectorAll

을 사용하면 된다.

// [h1, h1, h1] 이런 식으로 세개의 요소가 들어있는 배열을 반환해준다.

querySelectorAll은 조건에 부합하는 모든 요소를 가져온다.


first-child

const title = document.querySelector(".hello:first-child h1");

title.innerText = "Hello";

( .hello 의 첫번째 자식요소 인 h1 )
이런 모습으로도 요소를 지정할 수 있다.


console.log 와 비슷하게 생긴

console.dir 을 통해 요소의 내부를 볼 수 있다.


classList 메서드

  • add(String)
    지정한 클래스 값을 추가한다.
    만약 추가하려는 클래스가 이미 존재한다면 무시.
  • remove(String)
    지정한 클래스 값을 제거한다.
    존재하지 않는 클래스라면? 에러 발생 X
  • contains(String)
    지정한 클래스 값이 존재하는지 확인.
    true, false 값을 반환.
  • replace(old, new)
    old class를 new class로 대체
  • item(Number)
    인덱스 값을 활용하여 클래스 값을 반환

- toggle

클래스의 유무를 체크해서 없으면 add, 있으면 remove를 자동으로 해줌

profile
안녕하세여

0개의 댓글