Document - Object
HTML이 CSS와 JS를 가져온다는 건 국룰~
HTML의 Element들을 JS로 변경하거나 가지고 올 수 있다. (HTML과 상호작용)
마치 object내부에 있는 property들의 값들을 변경할 수 있다.
Console창에서 HTML코드를 JS관점에서 불러올 수도 있고, 수정도 가능
ex. document.title = "Hi" 라고 하면, 웹페이지 제목이 Hi로 변경됨.
여기서 document 는 웹페이지를 말하는 것. 그리고 Javascript의 시작점이라 말할 수 있다.
※ console.log(document) Vs console.dir(document)의 차이
console.log(document) -> 태그내용이 나온다. 우리가 보는 HTML의 구조
console.dir(document) -> document의 속성의 element의 내부들을 잘 자세히 보여준다.
참조. https://jongbeom-dev.tistory.com/115
[JavaScript] Console 객체 (2)
console.dir() log 함수 다음으로 가장 많이 사용하는 함수가 dir 함수이다. dir 함수는 객체의 속성을 계층구조로 출력한다. 대표적인 예제는 다음과 같다. 예제는 크롬 개발자도구의 콘솔창을 이용하
jongbeom-dev.tistory.com
HTML in Javascript (HTML 코드와 element를 JavaScript로 접근하는 방법)
Javascript코드로 id="title"을 가진 <h1>태그를 가져오기
getElementById() - 하나의 값
<h1 id="title">Grab me!</h1>
- 콘솔창 - document.getElementById("title)
- JS파일
// document함수중 getElementById라는 함수에 HTML id의 element들 찾는 방법
const title = document.getElementById("title");
console.log(title);
만약, console.log가 아니라 console.dir로 한다면,
element 내부들을 자세히 보여줄 수 있어 HTML의 element들을 가져와서 HTML코드에 추가 및 변경을 할 수 있지만, HTML 자체를 보여주지는 않는다.
element를 찾고나면, 그 HTML에서 뭐든지 바꿀 수 있다.
아래는 autofocus 와 classname을 추가한 것!
<h1 autofocus class="hello" id="title">Grab me!</h1>
아래는 innerText 이름을 변경한 것!
<h1 id="title">Grab me!</h1>
const title = document.getElementById("title");
title.innerText = "Got you!";
아주 중요한 개념!!!!!!
HTML에서 element들을 가지고 와서, JavaScript를 통해 element들을 변경
<h1 class="bllllaaa!!!!!" id="title">Grab me!</h1>
// document함수중 getElementById라는 함수에 HTML id의 element들 찾는 방법
const title = document.getElementById("title");
// element를 찾고나면, 그 HTML에서 뭐든지 바꿀 수 있다.
// 예, element의 innerText를 바꿀 수 있다.
title.innerText = "Got you!";
// h1 class와 id 를 콘솔창에서 볼 수 있다.
console.log(title.id);
console.log(title.className);
Searching For Elements
getElementByClassName() - 많은 element를 가져올 때 씀 (array를 반환)
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
<h1 class="hello">Grab me!</h1>
const hellos = document.getElementsByClassName("hello");
console.log(hellos);
getElementByTagName() - tagname을 할당할 수 있음 (array를 반환)
<div class="hello">
<h1>Grab me!</h1>
</div>
const title = document.getElementsByTagName("h1");
console.log(title);
getElemnetByName() - array를 반환
↑대신에 ↓사용
querySelector() - element를 CSS selector방식으로 검색할 수 있음. 단, 하나의 element만 return해줌.
// hello가 class name이라는 것고 그 안의 h1을 명시
const title = document.querySelector(".hello h1");
console.log(title);
querySelectorAll() - 이 selector 안의 조건에 부합하는 모든 element를 가져다줌.
<div class="hello">
<h1>Grab me 1!</h1>
</div>
<div class="hello">
<h1>Grab me 2!</h1>
</div>
<div class="hello">
<h1>Grab me 3!</h1>
</div>
// hello라는 class 내부의 h1태그가 여러개인 경우
const title = document.querySelectorAll(".hello h1");
console.log(title);
요약
// hello라는 class 내부의 h1태그인 경우
const title = document.querySelector(".hello h1");
// Css selector 사용하여 검색가능 ex. hi: first-child
const title = document.querySelector(".hello h1:first-child");
// querySelector #hello === getElementById hello
const title = document.querySelector("#hello");
const title = document.getElementById("hello");
console.log(title);
Events
// class hello를 가진 div 내부의 first-child인 h1을 찾아오는 것
const title = document.querySelector(".hello:first-child h1");
console.log(title);
여기서 h1태그의 내부들을 보고 싶으면, console.dir(title)을 한다.
const title = document.querySelector(".hello:first-child h1");
console.dir(title);
// title h1내부의 style 내부의 color항목을 변경
title.style.color = "blue";
그 내부들을 다 Events or JavaScript Object라 해당한다.
그 element 중 앞에 on이 붙은 것들은 eventlistener(어떤 행위를 하는 것)
모든 event들은 JS가 listen할 수 있다. (eventListener)
=== eventListener : event를 listen함 → JS에게 무슨 event를 listen하고 싶은 지 알려줘야 함
event를 listen하는 방법
const title = document.querySelector(".hello:first-child h1");
// 그래서 handle~함수에 ()를 안넣은 것임. (): 실행버튼을 누를 수 있다
// 즉, JS가 나 대신 실행버튼을 눌러주게 하는 것.
function handleTitleClick() {
console.log("title was clicked!");
}
// 누군가가 title을 click하면, handleTitleclick이라는 function이 동작하길 원함.
title.addEventListener("click", handleTitleClick);
설명▶ title이란 HTML element가 하나 있다고 가정하고 addEventListener를 호출하고, listen하고 싶은 event이름을 알려줄 것. event를 찾는 법은 나중에... 그리고 handleTitleClick이란 곳에 event가 발생하면 호출할 function을 전달해주면 된다. 주의!!! 우리가 실행버튼을 누르지 않고 JS가 해주길 바라기 때문에 () 넣음.
예제 1.
<div class="hello">
<h1>click me!</h1>
</div>
const title = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
title.style.color = "blue";
}
title.addEventListener("click", handleTitleClick);
event를 찾는 법 (What events you can listen for)
element의 이름 ex. h1 element을
- 구글에 h1 html element mdn 검색! ▶ Web API가 포함된 페이지를 클릭! ▶ HTMLElement 상자 or Element를 클릭!
- console.dir(해당하는 element) 입력해서 콘솔창에서 수많은 events항목들을 보게 될 것. 이 event들을 사용할 것. 단, 수많은 event들 중 on이 붙어있는 항목들은 ex. onabort를 abort로 사용해야 할 것.
const title = document.querySelector(".hello:first-child h1");
console.dir(title);
function handleTitleClick() {
title.style.color = "blue";
}
function handleMouseEnter() {
title.innerText = "Mouse is here!";
}
function handleMouseLeave() {
title.innerText = "Mouse is gone!";
}
//위 아래 두가지 방법이 있으나, addEventListener를 사용하는 것이 좋다.
//removeEventListen인 것도 있으니....
title.addEventListener("click", handleTitleClick);
title.onClick = handleTitleClick;
title.addEventListener("mouseenter", handleMouseEnter);
title.onmouseenter = handleMouseEnter;
title.addEventListener("mouseleave", handleMouseLeave);
title.onmouseleave = handleMouseLeave;
예제2.
const h1 = document.querySelector(".hello:first-child h1");
console.dir(h1);
function handleTitleClick {
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!!!");
}
// hi 와 document.title은 다르다.
// document 와 window 은 다르다.
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);
★ document의 body / document.head /document.title ~~ etc (O)
document.div (X)
나머지 element들은 querySelector나 getElementById로 불러와야됨!!!!!!!
CSS in JavaScript
- 사용자가 title을 click했을 때 title을 파란색으로 → 한번 더 눌렀을 때 title의 색깔을 tomato색깔로 변경하고 싶을 때
절차 (1) 콘솔창에서 확인하기
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// h1의 color를 획득할 수 있음 (getter)
console.log(h1.style.color);
// h1의 color를 blue로 설정.
h1.style.color = "blue";
// h1의 color를 다시 가져올 수 있음. (setter)
console.log(h1.style.color);
}
h1.addEventListener("click", handleTitleClick);
콘솔창 확인!
절차 (2) 조건을 달기
const h1 = document.querySelector(".hello:first-child h1");
// h1.style.color가 blue라면, tomato로 변경해주세요.
// h1.style.colr가 blue 아니라면, blue로 변경해주세요.
function handleTitleClick() {
if (h1.style.color === "blue") {
h1.style.color = "tomato";
} else {
h1.style.color = "blue";
}
}
h1.addEventListener("click", handleTitleClick);
브라우저 확인!
절차 (3) 코드를 간결하게
// 1. element를 찾기
const h1 = document.querySelector(".hello:first-child h1");
// 3. 그 event에 반응하기
function handleTitleClick() {
// h1.style.color를 현재상태라고 (기본)저장해보자.
const currentColor = h1.style.color;
// h1.style.color를 새로운색깔상태로 값을 변경했으니 newColor: 아무것도 없는 let 변수로 이용
let newColor;
if (currentColor === "blue") {
newColor = "tomato";
} else {
newColor = "blue";
}
// 앞의 조건에 해당하는 걸 거치면서 할당받는 값을 h1에 넣어준다.
h1.style.color = newColor;
}
// 2. event를 listen하기
h1.addEventListener("click", handleTitleClick);
- 브라우저에서 JavaScript, HTML, CSS와의 관계
- 방법1. CSS에 정의된 class name들로 HTML element에서 숨기고 표시하는 방법
절차 (1) JavaScript -> HTML -> CSS 과정
body {
background-color: beige;
}
h1 {
color: cornflowerblue;
}
.active {
color: tomato;
}
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// h1에 active class를 전달해 주고 싶다.
h1.className = "active";
}
h1.addEventListener("click", handleTitleClick);
절차 (2) h1.className은 getter이면서 setter이다.
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// 콘솔창에서 getter인 것은 className의 현재값 (getter)
console.log(h1.className);
// 만약 콘솔창에서 h1 class="lalala"라고 지정.
// 콘솔창에서 다시 클릭했을 때 지정한 값대로 나오기 때문에 (setter)
}
h1.addEventListener("click", handleTitleClick);
절차 (3) 조건을 달기
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// h1의 calssName이 active라면, class를 제거하고 싶다.
// h1의 className이 active가 아니라면, active하고 싶어요.
if (h1.className === "active") {
h1.className = "";
} else {
h1.className = "active";
}
}
h1.addEventListener("click", handleTitleClick);
절차 (4) 코드를 간결하게
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// clicked 단어스펠링 오류실수를 범하지 않기 위해 clickedClass라고 지정하자.
// CSS에서 한번만 clicked와 연결된다.
const clickedClass = "clicked";
if (h1.className === clickedClass) {
h1.className = "";
} else {
h1.className = clickedClass;
}
}
h1.addEventListener("click", handleTitleClick);
body {
background-color: beige;
}
h1 {
color: cornflowerblue;
transition: color 0.5s ease-in-out;
}
.clicked {
color: tomato;
}
여기서 잠깐!... sexy-font class를 넣어주고, h1 class에서 'sexy-font'를 계속 남겨두고, 'clicked'만 변경하고 싶다면,
classList를 이용하되. classList.contains()를 이용한다.classList 는 class들의 목록으로 작업할 수 있게 도와주는 역할이다.
body {
background-color: beige;
}
h1 {
color: cornflowerblue;
transition: color 0.5s ease-in-out;
}
.clicked {
color: tomato;
}
.sexy-font {
font-family: "Courier New", Courier, monospace;
}
<h1 class="sexy-font">Click me!</h1>
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
const clickedClass = "clicked";
// className은 모든 class들을 변경해버리는 특징이 있다.
// classList는 class들의 목록으로 작업할 수 있게 도와줌.
// classList에는 함수들 중 contains함수가 있다.
// contains함수는 '우리가 명시한 class가 HTML element의 class에 포함되어 있는지'
// 즉, classList가 clicked를 포함하고 있는지
if (h1.classList.contains(clickedClass)) {
h1.classList.remove(clickedClass);
} else {
h1.classList.add(clickedClass);
}
}
h1.addEventListener("click", handleTitleClick);
콘솔창에서 sexy-font 제외 clicked만 변하는 것을 알 수 있다.
- 방법2. toggle함수를 이용하는 방법
그러나, contains함수는 흔한 함수이다.
toggle함수는 classList에 classname이 이미 있는지 확인해서 존재여부에 따라 기능이 생성된다. 그래서 앞에 적은 contains함수와 달리 더 간결하게 toggle함수 하나로 쓸 수 있다.
const h1 = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
// toggle함수는 h1의 classList에 clicked class가 이미 있는지 확인해서
// 있다면, toggle이 clicked를 제거해주고,
// 없다면, toggle이 clicked를 classList에 추가해준다.
h1.classList.toggle("clicked");
}
h1.addEventListener("click", handleTitleClick);
'개발언어 > JavaScript' 카테고리의 다른 글
Clock만들기 (0) | 2021.09.01 |
---|---|
Login만들기 (0) | 2021.09.01 |
Conditionals : 조건문 (if,else) (0) | 2021.08.25 |
Function(코드를 캡슐화해서, 실행을 여러번 가능) (0) | 2021.08.25 |
Objects [설명이 필요한 정보가 담긴 데이터 리스트들] (0) | 2021.08.24 |