본문 바로가기

JavaScript

[자바스크립트] 정리 2

Javascript에서는 document 객체를 통해 HTML의 각 요소에 대해 접근할 수 있다.

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

 

Javascript에서 document 객체를 통해 HTML element를 가지고 오는 방법은 여러가지 있는데

가장 강력한 건 css selector를 이용하는 querySelector 이다. 

하위 항목을 검색할 수 있고 여러개일 경우 HTML 문서에서 가장 상위의 것을 가지고온다. 

querySelectorAll은 여러개이면 배열에 담아서 가지고 온다. 

const title = document.querySelector("#hello"); // css selector를 이용하여 검색
const title = document.getElementById("hello"); 

const title = document.querySelector(".hello");
const title = document.getElementsByClassName("hello");

const title = document.querySelector(".hello h1"); // class = hello의 h1

 

Event 등록하고 사용하기 

addEventListener(event, 함수) -> 권장, 나중에 삭제하기도 용이

onst title = document.querySelector("div.hello:first-child h1");
title.innerText = "hello"
console.log(title);
console.dir(title); // 객체를 콘솔에 띄울 때 
					// property 앞에 on 이 있으면 eventListener, onmouseenter, onclick 등등... 

function handleTitleClick(){
    console.log("h1 was clicked!");
    h1.style.color = "blue";
}

function handleMouseEnter(){
    h1.innerText = "Mouse is here!"
}

function handleMouseLeave(){
    h1.innerText = "Mouse is leave!"
}

function handleWindowResize(){
    document.body.style.backgroundColor = "tomato";
}

function handleWindowCopy(){
    alert("Copide!")
}

function handleWindowOffline(){
    alert("Wify Out!");
}

function handleWindowOnline(){
    alert("Wify On!");
}

h1.addEventListener("click", handleTitleClick); // () 필요없음 실행은 Javascript가 해준다. 
h1.addEventListener("mouseenter", handleMouseEnter); // () 필요없음 실행은 Javascript가 해준다. 
h1.addEventListener("mouseleave", handleMouseLeave); // () 필요없음 실행은 Javascript가 해준다. 

window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy", handleWindowCopy);
window.addEventListener("offline", handleWindowOffline);
window.addEventListener("online", handleWindowOnline);


// title.onclick = handleTitleClick; 이렇게도 등록 가능 
// property 앞에 on 이 있으면 eventListener

HTML의 title, body, head 등은 document.body 와 같이 바로 접근할 수 있다. 나머지는 querySelector로 접근한다. 

doucument 객체처럼 window객체도 기본적으로 제공한다.

어떠한 event들이 있는지 보려면 공식문서를 참조한다.  

 

Window - Web API | MDN (mozilla.org)

 

문서의 style을 바꿀때 Javascript에서 하는 것보다는 css로 하는 것이 좀더 일반적인 방법이다. 

그러기 위해서 여러 className을 정의하고 classList 에 존재하는지 여부를 통해 css를 적용한다.

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

// function handleTitleClick(){
//     const activeClass = "active"
//     if(h1.classList.contains(activeClass)){
//         h1.classList.remove(activeClass);
//     } else{
//         h1.classList.add(activeClass);
//     }
// }

function handleTitleClick(){
    h1.classList.toggle("active"); // if active is not in classList and or remove!
}

h1.addEventListener("click", handleTitleClick);

classList에 특정 className을 추가하고 제거하는것은 매우 자주 일어아는 일이다. 

따라서 toggle이란 함수를 이용하여 한줄로 해결하자. 

'JavaScript' 카테고리의 다른 글

[자바스크립트] 정리 6  (0) 2022.01.19
[자바스크립트] 정리5  (0) 2022.01.18
[자바스크립트] 정리4  (0) 2022.01.18
[자바스크립트] 정리3  (0) 2022.01.18
[자바스크립트] 정리 1  (0) 2022.01.15