document.getElementByid("title")
document.getElementByid()는 html에 있는 id를 불러올 수 있다.
title.innerText="hi"
처럼 javascript에서 html에 있는 id를 사용해 내용 수정이 가능하다.
모든 것들은 html에서 항목들을 가지고와서 javascript에서 변경한다.
getElementsByClassName() getElementsByTagName() querySelector()
getElementsByClassName(): 많은 element를 가져올때 사용한다(array를 반환)
getElementsByTagName(): name을 할당할 수 있다.(array를 반환)
querySelector(): elemen를 CSS selector방식으로 검색할 수 있다.(ex. h1:first-child)
querySelectorAll(): 조건에 맞는 것들을 다 가져온다.
javascript 파일이 있어야 javascript를 통해 html의 내용을 가져올 수 있다.
document가 html이 javascript파일을 load하기 때문에 존재하고
그 다음으로 browser가 document에 접근할 수 있게 해준다.
element의 내부를 보고 싶으면
console.dir()
기본적으로 object로 표시한 element를 보여줌(전부 javascript object이다.)
그 중 앞에 on으로 시작하면 event이다.
모든 event는 javascript가 listen할 수 있다.
eventListener()
eventListener: event를 listen한다 -> javascript에게 어떤 event를 listen하고 싶은지 알려줘야 한다.
title.addEventListener("click")
title.addEventListener("click"): 사용자가 title을 click하는 것을 listen할 거다. -> 무언가를 해주어야한다.
const title = document.querySelector("div.gello:first-child h1"); function handleTitleClick(){ title.style.color="blue" } title.addEventListener("click", handleTitleClick); // handleTitleClick에서 옆에 ()를 안써주는 이유는 자동으로 실행하는것을 막기 위함이다.
-click하면 handleTitleClick이라는 function이 동작하길 원한다.
(javascript가 실행시키도록 한다.)
listen하고 싶은 event를 찾는 가장 좋은 방법은
element의 이름, 예를 들면 h1 html element mdn을 검색하고
javascript의 element를 원하니, Web APIs라는 문장이 포함된 페이를 찾는다.
title.onclick = handleMouseEnter; title.addEventListener("mouseenter", handleMouseEnter);
위 두 코드는 기능은 동일하지만 addEventListener사용을 더 선호한다.
그 이유는 removeEventListener을 통해서 event listener을 제거해줄 수 있기 때문이다.
document에서 body, head, title은 중요해서
언제든 document.body로 가져올 수 있다.
div, h1등 element들은 querySelector getElementByid 등으로 찾아야 한다.
ex. document.querySelector("h1")
//css 파일에서 색을 지정해서 사용한 예시 const h1 = document.querySelector("div.hello:first-child h1"); function handleTitleClick() { const clickedClass = "clicked"; //css 에서 색 명시함 if (h1.classList.contains(clickedClass)) //contains는 true, false 값을 반환 한다. h1.classList.remove(clickedClass); } else { h1.classList.add(clickedClass); } } h1.addEventListener("click", handleTitleClick);
const h1 = document.querySelector("div.hello:first-child h1"); function handleTitleClick() { h1.classList.toggle("clicked"); } h1.addEventListener("click", handleTitleClick);
위 두가지 코드는 같은 기능을 하지만 아래 코드에서 toggle을 사용 함으로써
function부분을 한줄로 작성하였다.
h1의 classList에 clicked class가 이미 있는지 확인해서 만약 있다면, toggle이 clicked를 제거해준다. 반대일 경우엔 toggle이 clicked를 classList에 추가를 해준다.
감사합니다😊