www.w3schools.com/howto/howto_js_toggle_dark_mode.asp
inline방식
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>자바스크립트를 통해 html을 제어해보자</title>
<style>
#selected{
color:red;
}
.dark{
background-color: black;
color:white
}
.dark #selected{
color:yellow
}
</style>
<!-- <script>
function darkBackground(){
document.body.classList.toggle("dark")
}
</script> -->
</head>
<!-- <body class="dark"> -->
<body class="">
<ul>
<li>HTML</li>
<li>CSS</li>
<li id="selected">Javascript</li>
<!-- <input type="button" value="어두운배경버튼" onclick="darkBackground()"> -->
<input type="button" value="darkbtn" onclick="document.body.classList.toggle('dark');">
</ul>
</body>
</html>
body를 선택하고싶을땐
document.body
document.body.classList("dark")
문서에 body태그안에 dark라는 클래스를 넣겠다~
클래스명을 변경+토글하고싶을때
document.body.classList.toggle("클래스명")
script태그
주의할점! body태그안 하단에 위치하지않을경우
Cannot read property 'addEventListener' of null
이라는 오류메시지 출력하기때문에 script태그 위치주의
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>자바스크립트를 통해 html을 제어해보자(script태그)</title>
<style>
#selected{
color:red;
}
.dark{
background-color: black;
color:white
}
.dark #selected{
color:yellow
}
</style>
</head>
<!-- <body class="dark"> -->
<body class="">
<ul>
<li>HTML</li>
<li>CSS</li>
<li id="selected">Javascript</li>
<!-- <input type="button" value="어두운배경버튼" onclick="darkBackground()"> -->
<input type="button" value="darkbtn" id="darkbtn">
</ul>
<script>
var darkbtn = document.querySelector('#darkbtn')
darkbtn.addEventListener('click', () => {
document.body.classList.toggle('dark')
});
</script>
</body>
</html>
head태그 안에위치하고싶다면?
1. onload매소드 호출(가급적 바디태그 뒤에다가하는것이 바람직)
window.onload=function(){
};
2.defer, async공부~
ko.javascript.info/script-async-defer
반응형
'Frontend > dom' 카테고리의 다른 글
attribute로 속성 조정하기(+jquery attr) (0) | 2021.05.09 |
---|---|
클래스 제어(classList) (0) | 2021.05.09 |
제어대상찾기(querySelector, querySelectorAll) (0) | 2021.05.09 |
insertAdjacentHtml(position, text), parentNode (0) | 2020.10.09 |
[Node/dom] appendChild(),createElement(),removeChild() (0) | 2020.10.05 |