3.2 Searching For Elements

gangmin·2021년 12월 19일
0

강의

많이 저지르는 실수

  <body>
    <h1 class="hi">Grab me!</h1>
    <script src="app.js"></script>
  </body>
const title = document.getElementById("title");
title.innerText = "Got you!"

위의 코드는 에러가 생긴다.
Cannot set properties of null (setting 'innerText')
= 코드 내에 어떤 값이 null이라는 뜻. 근데 우리는 아무것도 없는(null)의 innerText를 접근하려고 한거다.

JS코드를 보면, title이란 id를 가진 항목이 없기 때문이다.
= 변수 title은 null인데 우린 지금 null의 innerText를 변경하려고 했기 때문이다.


getElementsByClassName

저번 시간에 id를 활용해서 JS에서 HTML 요소들을 불러왔다. 그렇지만, 대부분의 경우에는 id를 추가하지는 않을거다. id를 사용하기 편리하지만, 보통 className을 사용하거나 둘다 사용하기 때문이다.

getElementsByClassName : 클래스에 해당되는 모든 요소들을 불러온다.

  <body>
    <h1 class="hi">Grab me!</h1>
    <h1 class="hi">Grab me!</h1>
    <h1 class="hi">Grab me!</h1>
    <script src="app.js"></script>
  </body>
const hellos = document.getElementsByClassName("hello");
console.log(hellos);

콘솔창에 모든 h1 elements가 나오는데, array로 나온다.
즉, hellos.xx 으로 뭔가를 가져올 수 없다. object가 아닌 array라 활용이 안된다.
가끔 많은 element를 한번에 가지고 와야하는 경우가 있을때 사용하면 된다. ㅇㅇ

그렇지만, 대부분의 경우에는 class name을 모든 곳에 추가하지는 않을거다.


getElementsByTagName

getElementsByTagName : tag name에 해당되는 모든 요소들을 불러온다.

<div class="hello">
  <h1>Grab me!</h1>
</div>
const title = document.getElementsByTagName("h1");
console.log(title);

bject로 나오는게 아니라 array라서 뭘 적용시킬수 없다.
tag에는 anchor, div, section, button 같은 것들을 의미한다.


querySelector, querySelectorAll

니꼬 기준 element를 가져오는 최고의 방법은 querySelector, querySelectorAll 이다.

querySelector : element를 css방식으로 검색할 수 있다.

<div class="hello">
   <h1>Grab me!</h1>
</div>
const title = document.querySelector(".hello h1");
console.log(title);

hello라는 class 내부에 있는 h1을 가지고 올 수 있다는것을 의미한다!!
class="hello"를 찾고, 그 안에 있는 h1을 가져와달라고 할거다.

그 결과..

<h1>Grab me!</h1>

아주 잘가져온다!!!

이건 앞서 언급한 2개의 함수와 다르다. 배열로 들고오는게 아니라 css처럼 요소를 들고 오기 때문에 더 섹시하다. 단 하나의 element를 return 해준다.

const title = document.querySelector(".hello h2"); 라고 한다면 null을 반환한다.
(h2 요소가 없으면 undefined가 출력되어야 하는게 아닌가...? 잘모르겠네...)

class="hello"안에 h1이 많을 수도 있다. 그렇다면 조건에 맞는 모든 요소들을 들고오는가? 아니다. 오직 첫번째것만 가져온다.조건에 부합하는걸 모두 들고오고싶다면 querySelectorAll을 사용해주면 된다. 근데 array로 가져온다.

+) querySelector(".hello h1:first-child"); 이렇게도 할 수 있다!!

이거는 id로도 찾을 수 있다. ("#hello"); 이렇게 해주면 된다.

const title = document.querySelector("#hello");
const title = document.getElementById("hello");

함수는 다르지만 같은 결과값을 가진다!

0개의 댓글