TIL(2022.2.10)- [JS] element를 가져오는 방법 및 Event

박세진·2022년 2월 10일
0

Javascript로 Html element를 가져오려면 어떻게 해서 가져오는 방법

<body>
  <h1 id= 'title'>HTML이란?</h1>
  <h2 class='items'>아이템</h2>
  <h2 class='items'>아이템</h2>
  <h2 class='items'>아이템</h2>
  <h2 class='items'>아이템</h2>
  <h2 class='items'>아이템</h2>
</body>
  • <h1> element를 가져오고 싶은 경우, getElementById 함수를 이용해서 id 선택자를 가져올 수 있다.
document.getElementById('title');
  • class 선택자를 가져오고 싶은 경우, getElementByClassName 함수를 이용해서 class 선택자를 가져올 수 있다.
document.getElementByClassName('items');
// [h2.items, h2.items ...] 배열로 반환
  • 위 두 가지 방법도 있지만, 가장 편리하고 많이 사용하는 document.querySelector, document.querySelectorAll이 있다.
    • document.querySelector는 단 하나의 elemen를 return!
    • CSS 선택자 작성하는 방법과 똑같다.
<body>
  <div id='title'>
    <h1>Wash your hands</h1>
	<h2 class= 'items'>water</h2>
    <h2 class= 'items'>soap</h2>
    <h2 class= 'items'>towel</h2>
  </div>
</body>
const title = document.querySelector('#title h1');

const items = document.querySelectorAll('.items');
console.log(items);
// [h2.items, h2.items, h2.items] 배열 반환

js로 html 내용 변경하고 싶다면?

위의 코드를 가지고 변경하는 코드를 적을 것이다.

title.innerText = '손을 씻기 위한 준비물';

Event

이벤트는 마우스 클릭, 키보드를 누르거나, 브라우저의 크기를 조정하는 등 사용자의 액션에 의해 발생하거나 비동기적 작업의 진행을 나타내기 위해서 api가 생성하기도 한다.

다양한 종류의 event들이 있는데, event를 javascript가 listen하게 할 수 있다.

  • .addEventListener() : 지정한 유형의 이벤트가 발생하면 호출할 함수를 전달한다.
const h1El = document.querySelector('#title h1');

function handleH1ElClick () {
	alert('Click!!!!');
};

title.addEventListener('click', handleTitleClick);

// 작성할 때 주의할 점!
title.addEventListener('click', handleTitleClick());
// 이렇게 쓰면 안된다!!! 

오늘 배운 내용은 노마드 코더 '바닐라 Js로 크롬앱 만들기' 무료 강의를 듣고 배운 내용이다. 당분간은 열심히 js 2주 챌린지를 하기 때문에 TIL 내용은 대부분 크롬앱 만들기 하면서 새롭게 배운 내용들 위주로 간단하게 정리할 것이다.

profile
경험한 것을 기록

0개의 댓글