const h1 = document.querySelector("div.hello:first-child h1");
h1.innerText = "Click ME!";
function handleTitleClick(){
const currentColor = h1.style.color;
let newColor;
if(currentColor === "blue") {
newColor = "tomato";
} else {
newColor = "blue";
}
h1.style.color = newColor;
}
h1.addEventListener("click", handleTitleClick);
let newColor; ๋ผ๋ ๋น ๋ณ์๋ฅผ ์ค ์ด์ : const๋ฅผ ์ฌ์ฉํ์ฌ currentColor๋ฅผ ์ ์ํ๋ฉด ๊ฐ์
๋ณ๊ฒฝํ ์ ์๊ธฐ ๋๋ฌธ์ let์ผ๋ก ๋น ๋ณ์๋ฅผ ๋ง๋ค์ด ์ค.
์ดํ์ newColor = "tomato";๊ฐ ์ค์ ๋ก ์คํ์ ๋์์ผ๋ newColor๊ฐ ๋ฌด์์ธ์ง ์ ์๋์ด์์ง ์์ ๋์ ๋ณด์ด๋ ์์์ด ๋ณํ์ง ์์.
๋ฐ๋ผ์ h1.style.color = newColor;๋ผ๋ ๋ณ์๋ฅผ ์ถ๊ฐํ๋ค.
๋ฐ๋๋ก newColor = h1.style.color; ๋ ์ ์๋๋์ง ๋ชจ๋ฅด๊ฒ ์
๊ทธ๋ฌ๋ ์๋ฐ์คํฌ๋ฆฝํธ์์ css๋ฅผ ์ฝ๋๋ก ์ง์ ๋ฐ๊พธ๋ ๊ฒ์ ๋ณ๋ก ์ข์ ๋ฐฉ๋ฒ์ด ์๋
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
const activeClass = "active"
if(h1.className === activeClass) {
h1.className = "";
} else {
h1.className = activeClass;
}
}
addEventListener("click", handleTitleClick);
์คํ์ ์ ๋๋ ๋ฒ๊ทธ๊ฐ ํ๋ ์กด์ฌํจ
๋ง์ฝ h1์ "active" ์ด์ธ์ ์ด๋ฏธ ์กด์ฌํ๋ ํฐํธ๋ฅผ ๋ณ๊ฒฝํ๋ class๊ฐ ์๋ค๋ฉด,
click์ด๋ฒคํธ๋ฅผ ์คํํ ๋ ํฐํธ class๋ฅผ ์์ ๋ฒ๋ฆผ.
์ฆ, ๋ช
๋ น์ด๋๋ก๋ง class๋ฅผ ๋จ๊ธฐ๊ณ ๋๋จธ์ง ๋ชจ๋ class๋ ์๋ ์กด์ฌ๊ฐ ๋์ด๋ฒ๋ฆฐ๋ค..
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
const activeClass = "active";
if (h1.classList.contains(activeClass)) {
h1.classList.remove(activeClass);
} else {
h1.classList.add(activeClass);
}
}
h1.addEventListener("click", handleTitleClick);
className์ด ์๋ classList๋ฅผ ์ถ๊ฐํ์ฌ ์ ๋ฒ๊ทธ๋ฅผ ํด๊ฒฐํ ์ ์๋ค.
h1.classList.contains(activeClass) -----> h1.classList์ activeClass๊ฐ ํฌํจ๋์ด ์๋ค๋ฉด,
h1.classList.remove(activeClass); -----> h1.classList์ activeClass๋ฅผ ์ ๊ฑฐํด๋ผ.
else {
h1.classList.add(activeClass);
}
-----> ๋ง์ฝ,h1.classList์ activeClass๊ฐ ํฌํจ๋์ด ์์ง ์๋ค๋ฉด h1.classList์ activeClass๋ฅผ ์ถ๊ฐํด๋ผ.
๊ทธ๋ฌ๋ ์ด ์ฝ๋๋ toggle์ ์ฌ์ฉํ์ฌ ์ค์ผ ์ ์์
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick() {
h1.classList.toggle("active");
}
h1.addEventListener("click", handleTitleClick);
toggle์ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ๊ฐ๋จํ๊ฒ ์ค์. (if๋ฌธ๋ ์ฌ์ฉx)
const activeClass ="active"; ์ ๋ณ์๋ ์์ ๋ฒ๋ฆผ.(์๋๋ฉด "active"๋ฅผ ํ๋ฒ๋ง ์ฌ์ฉํ๋๊น ๋ณ์๋ก ์ง์ ํ ํ์๊ฐ ์์.)
div.hello:first-child h1
-> div.hello :first-child
querySelector ๋ถ๋ถ์ ์์ ํด์ผํฉ๋๋ค. ๋ ธ๋ง๋์ฝ๋์์ ์๋ชป์๋ด์ค..