JavaScript Searching For Elements!
우리는 대부분 id를 추가하는것 보다는 보통 className을 사용하거나 둘다 사용하려고한다
우리의 코드 내에 어떤값이 null이라는 뜻인 오류코드!
왜냐하면 아무것도 없는 것(null)의 innerTect에 접근하려고 했기때문에
<body>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<script src="app.js"></script>
</body>
지금 ch1의 class는 "hello" 인데
const title = document.getElementById("something");
title.innerText = "Got you! "
console.log(title.className);
왜냐하면 something이라는 id를 가진 항목이 없기 때문에 title = null 이고 title 내부의 (null인것)에 innertext 를 하였기떄문에 오류가 나온것이다.
가끔 많은 element를 한번에 가지고 와야하는 경우에는
getElementByClassName()을 사용하면된다!
<div class="hello">
<h1>Grab me!</h1>
</div>
여기서 h1을 가져오기 위해서는 또다른 function이 필요하다
HTML안에 있는 모든 H1을 가져오기 위해서는 getElementByTagName("h1");
const title = document.getElementsByTagName("h1"); //to get all of H1
console.log(title);
getElementByTagName으로는 모든 태그를 가져올수 있다. ex) anchor, div, section , button
querySelector: element를 CSS방식으로 검색할수 있다.
정리: 이번 에는 getElementsByClassName도 배웠고 이것은 array를 가져다준다.
getElementByTagName 이것또한 array로 반환한다.
getElementByName도 있다.
querySelector는 CssSelector을 사용하여 검색할수 있따.
예를 들어 h1:first-child도 가능하다 -> 이것은 첫번쨰로 검색된 element만 return!
Id를 찾을때도 querySelector로 찾을수 있다 아이디 셀렉터는 # 이다.
주의할점은 querySelctor("#hello"); 는 우리가 뭘 검색하는지 명확하지 않으니까 id(#)를 명시해줘야한다.
getElementById("hello"); 는 여기서 우리가 id를 찾고 있다는걸 알고 있어서 #을 하지 않아도 된다.