TIL 16 - 문서제어

hojung choi·2021년 6월 23일
0

js

목록 보기
1/17

📌 노드 객체 가져오기

document는 객체이다.
이러한 객체에는 요소 객체를 가져올 수 있는 메서드가 있다.
메서드들을 살펴보자!

👉🏻 getElementById

document.getElementById("id 값");

👉🏻 getElementByTagName

document.getElementByTagName("요소의 태그 이름");

👉🏻 getElementByClassName

document.getElementByClassName("class의 이름");

👉🏻 querySelector

document.querySelector("선택자");

선택자 요소의 직계 자식 요소 중 첫번째 요소를 반환한다

👉🏻 querySelectorAll

document.querySelectorAll("선택자");

<div class="hello">
   <h1>1</h1>
   <h1>2</h1>
   <h1>3</h1>
</div>
const hello = document.querySelectorAll(".hello h1");
console.log(hello);

선택자 요소의 직계 자식 요소를 배열로 담는다!

const hello = document.querySelectorAll(".hello h1");

console.log(hello);

hello[1].style.color = "red";

hello는 배열이므로, style를 제어 하기 위해서는 배열과 같이 []를 사용하여 style를 제어한다.




📌 이벤트 리스너

이벤트 리스너들은 일일히 다 외우는 것 보다 상황에 맞게 찾아보는게 좋다!
아 mdn페이지를 참고하여 사용하자!

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
https://developer.mozilla.org/en-US/docs/Web/API/window

🚫 예제로 풀어봤던 이벤트 리스너

const h1 = document.querySelector(".title h1");

const handleTitleClick = () => {
    console.log("title was clicked!");
}

const handleMouseEnter = () => {
    title.innerText = "mouse is here!";
}

const handleMouseLeave = () => {
    title.innerText = "mouse is gone!";
}

const handleWindowCopy = () => {
    alert("copier!");
}

const handleWindowoffline = () =>{
    alert("wifi sos");
}

h1.addEventListener("click", handleTitleClick); //  h1.onclick = handleTitleClick;
h1.addEventListener("mouseenter", handleMouseEnter); // h1.onmouseenter = handleMouseEnter;
h1.addEventListener("mouseleave", handleMouseLeave); // h1.onmouseleave = handleMouseLeave;

window.addEventListener("copy", handleWindowCopy);
window.addEventListener("offline", handleWindowoffline);
profile
🧚🏻‍♀️ Front-End Developer

0개의 댓글