TIL 210629

jm·2021년 6월 29일
0

공부한 내용

https://nomadcoders.co/javascript-for-beginners 강의 중 일부

HTML 요소를 Javascript로 접근하는 방법

서버와 통신을 하거나 다른 복잡한 일들을 처리할 때 js 파일에서 처리하게 되는데 그때 HTML의 element들을 자유자재로 다룰 수 있게 되야 여러 복잡한 처리를 원할하게 할 수 있게 됨

// HTML
<body>
  <h1 id="title" class="hello">Grab me!</h1>
  <script src="app.js"></script>
</body>
const title = document.getElementById("title");
console.dir(title);

주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 요소를 반환함

console.log, console.dir

  • console.log는 요소를 HTML과 같은 트리 구조로 출력함
  • console.dir은 요소를 JSON과 같은 트리 구조로 출력함

JavaScript에서 HTML 요소 변경하기

const title = document.getElementById("title");
title.innerText = "Got you" ;

Searching For Elements

// html
<div class="hello">
  <h1>Grab me!</h1>
</div>
const hellos = document.getElementsByClassName("hello");

getElementsByClassName 많은 요소를 한번에 가지고 와야하는 경우에 사용

  • console.log를 사용하면 h1이 들어있는 array를 출력함
const title = document.querySelector(".hello h1"); 

querySelector 요소를 CSS 방식으로 검색할 수 있음, 단 하나의 요소를 리턴함
→ 'hello'란 class내부에 있는 h1을 가지고 올 수 있음

  • console.log를 사용하면 첫 번째 h1 요소만 출력 됨

querySelectorAll 셀렉터 안의 조건에 부합하는 모든 요소를 배열로 출력함

Events

console.dir 실행시 이름 앞에 on이 붙어있으면 event listener

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

function handleTitleClick() {
  title.style.color = "blue";
}

title.addEventListener('click', handleTitleClick);

addEventListener() 지정한 이벤트가 대상에 전달될 때마다 호출할 함수를 설정함

  • 클릭시 handleTitleClick라는 함수를 실행함

또 다른 방법

title.onclick = handleTitleClick;

addEventListener가 유용한 이유

removeEventListener 통해 event listener를 제거할 수 있음

0개의 댓글