getElementById("id")
: id 요소를 가져옴innerText
: HTML 요소를 변경<h1 id="title">grab me!</h1>
document.getElementById("title") // <h1 id="title">grab me!</h1>
const title = document.getElementById("title")
title.innerText = "Got you!" // Got you!
console.log(title.id); //title
console.log(title.className); // empty
getElementByClassName()
사용(array)querySelector()
: element를 css 방식으로 검색 ✨querySelectorAll()
: selector 안의 조건에 부합하는 모든 element를 가져옴(array)<div class="Hello">
<h1>grab me!</h1>
</div>
const title = document.querySelector(".hello h1")
console.log(title) //<h1>grab me!</h1>
addEventListener("evnet, function")
: event가 발생하면 function을 실행시켜 준다.<div class="Hello">
<h1>grab me!</h1>
</div>
const h1 = document.querySelector(".hello h1")
console.dir(title); // element의 내부를 보여줌
fucntion handleTitleClick(){
h1.style.color = "blue";
}
fucntion handleMouseEnter(){
h1.innerText = "mouse is here!"
}
fucntion handleMouseLeave(){
h1.innerText = "mouse is gone!"
}
h1.addEventListener("click", handleTitleClick)
h1.onclick = handleTitleClick
// 위 두 코드는 동일하나 addEventListener를 더 선호하는 이유는 removeEventListener로 evett listenr를 제거할 수 있기 때문이다.
h1.addEventListener("mouseenter", handleMouseEnter)
h1.addEventListener("mouseleave", handleMouseLeave)
fucntion handleWindowResize(){
document.body.style.backgroundColor = "tomato";
}
fucntion handleWindowCopy(){
alert("copier!");
}
fucntion handleWindowOffline(){
alert("SOS no WIFI!");
}
fucntion handleWindowOnline(){
alert("All good");
}
window.addEventListener("resize", handleWindowResize) // 화면 조정
window.addEventListener("copy", handleWindowCopy) // 복사
window.addEventListener("offline", handleWindowOffline) // 와이파이 유무
window.addEventListener("online", handleWindowOnline)
참조 MDN
코딩챌린지
const title = document.querySelector("h2");
const superEventHandler = {
handleMouseEnter: function () {
title.innerText = "The mouse is here!";
title.style.color = colors[0];
},
handleMouseLeave: function () {
title.innerText = "The mouse is goen!";
title.style.color = colors[1];
},
handleWindowResize: function () {
title.innerText = "You just resized!";
title.style.color = colors[2];
},
handleContextMenu: function () {
title.innerText = "That was a right click!";
title.style.color = colors[3];
}
};
title.addEventListener("mouseenter", superEventHandler.handleMouseEnter);
title.addEventListener("mouseleave", superEventHandler.handleMouseLeave);
window.addEventListener("resize", superEventHandler.handleWindowResize);
window.addEventListener("contextmenu", superEventHandler.handleContextMenu);