자바스크립트에서 HTML 항목들에 접근할 수 있음
document.getElementById()
document.querySelector()
: 해당 element를 CSS방식(notatioin)으로 검색
ex. document.querySelector(.class이름 h1);
: 만약 같은 클래스를 가지고 있는 요소가 있다면, always brigs only '1st'element
document.querySelectorAll()
: brings selector 안의 조건에 부합하는 '모든'element
: .querySelectorAll(#id:first-child); 식으로 접근하는 것도 가능
console.dir()
: ()안 해당 element의 내부를 보고 싶을 때
: 그 떄 나오는 항목들은 전부 Javascript object임 !!
: 물론 자바스크립트에서 바꾸는 거라 새로 고침하면 기존 html로 돌아옴
: 콘솔에서 document의 body, head, title만 불러올 수 있음 - 나머지는 querySelector나 getElementById 로 찾아와야 함
const h1 = document.querySelector(".hello:first-child h1");
// console.dir(title);
title.style.color = "blue";
// element의 해당 요소를 직접적으로 바꿀수 있음
/// 대부분 JS에서 작업할 일은 event를 listen하는 것
: 대부분 js에서 작업할 일은 event를 listen 하는것
listen 하고 싶은 event를 찾아보는 방법
- google -> h1 html element mdn(Mozilla Developer Network )
console.dir(element)해서 나오는 prperty들 중에 'on'으로 시작하는 것들이 event listner들임 여기서 찾아써도 됨 ~(but 사용할땐 on 빼구 사용)
- mdn에 이렇게 써있당: Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.
function handleTitleClick() {
console.log("title was clicked!")
h1.style.color = "blue";
}
function handleMouseEnter() {
h1.innerText = "Mouse is here!";
}
function handleMouseLeave() {
h1.innerText = "Mouse is gone!";
}
function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {
alert("copier!");
}
function handleWindowOffline() {
alert ("SOS no Wifi");
}
function handleWindowOnline() {
alert ("ALL GOOOD");
}
h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);
다른 형태로도 가능
h1.onclick = handleTitleClick;
but 위에 방식을 선호하는 이유: event를 remove 할 수 있기 때문
h1.removeEventListner
테스트 풀 코드
const h1 = document.querySelector(".hello:first-child h1");
// console.dir(title);
function handleTitleClick() {
console.log("title was clicked!")
h1.style.color = "blue";
}
function handleMouseEnter() {
h1.innerText = "Mouse is here!";
}
function handleMouseLeave() {
h1.innerText = "Mouse is gone!";
}
function handleWindowResize() {
document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {
alert("copier!");
}
function handleWindowOffline() {
alert ("SOS no Wifi");
}
function handleWindowOnline() {
alert ("ALL GOOOD");
}
h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);
window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy",handleWindowCopy);
window.addEventListener("offline", handleWindowOffline);
window.addEventListener("online", handleWindowOnline);