<h1 id="first"></h1>
<li class="my-li"></li>
<li class="my-li"></li>
<li class="my-li"></li>
// window는 화면에 필요한 객체나 메소드들을 가지고 있는 최상위 객체
// window라는 객체는 보통 생략이 가능하다
// document는 화면의 html 전체문서를 뜻한다
// 태그들도 모두 객체이다
<ul>
<!-- class 속성값은 페이지에서 여러번 사용해도 된다 -->
<li class="my-li"></li>
<li class="my-li"></li>
<li class="my-li"></li>
</ul>
<!-- id 속성값은 페이지에서 유일해야한다 -->
<h1 id="first"></h1>
<h1 class="second"></h1>
<script>
// querySelector는 css 선택자를 이용해서 단일 태그를 가져온다
const firstTag = document.querySelector("#first");
firstTag.innerHTML = "첫번째입니다";
// querySelectorAll css 선택자를 이용해서 태그 리스트를 가져온다
const myLiTagList = document.querySelectorAll(".my-li");
// getElementById는 id 속성값을 기준으로 단일 태그를 가져온다
const firstTag = window.document.getElementById("first");
firstTag.innerText = "첫번째입니다.";
// getElementsByClassName은 class 속성값을 기준으로 태그 리스트를 가져온다
const myLiTagList = window.document.getElementsByClassName("my-li");
for (let i = 0; i < myLiTagList.length; i++) {
// 백틱은 문자열 포맷팅, 문자열 사이에 변수를 넣을 수 있다
myLiTagList[i].innerText = `${i}. 상품${i}`;
}
// querySelector가 단일 태그를 가져오는 점을 이용해서
// 클래스 선택자로도 태그 하나만을 가져와서 사용할 수 있다
const secondTag = document.querySelector(".second");
secondTag.innerText = '두번째입니다!';
</script>
<script>
const firstTag = document.querySelector("#first");
//태그의 속성을 객체의 프로퍼티처럼 가져온다.
console.log(firstTag.id);
firstTag.id = "next";
//태그에 없었던 속성도 만들어서 넣을 수 있다.
// className은 class 내용 전체
// classList는 class 내용을 띄어쓰기 기준으로 리스트
firstTag.className = "my-h1";
//firsttag.classname = "my-h1 red";
firstTag.classList.add("blue");
//태그가 가지고 있는 메소드를 정의 할 수 있다
fistTag.onclick = function(){
alert("click");
};
// 기존의 태그에 없던 변수도 만들 수 있다
firstTag.asdf = "새로운 변수";
firstTag.hello = () => {
alert("안녕하세요.");
};
// 기존 태그에 없던 함수도 만들 수 있다.
firstTag.hello = () => {
alert("안녕하세요");
};
// firsttag.asdt = "새로운 변수"; 는 작동이 안되는 브라우저가 있을수도 있다고 한다.
// 기존태그에 없던 변수나 함수는 위의 방식보다 아래방식으로 하는게 낫다.
firstTag.setAttribute("asdf","새로운 변수");
// 셋어트리뷰티는 key문자열 / value문자열이기에 아래 코드는 작동을 하지 않는다.
firstTag.setAttribute("hello", () => {
alert("안녕하세요");
});
// firstTag.getAttribute("hello")(); // 에러
</script>
<body>
<h1 id="first" onclick="alert('첫번째클릭')">첫번째</h1>
<h1 id="second" onclick="alert('두번째클릭')">두번째</h1>
<h1 id="third">세번째</h1>
<script>
// 이벤트 - 화면에 유저의 입력 등 움직임임을 주는 것들.
// 마우스, 키보드 , 음성, 카메라
const third = document.querySelector('#third');
third.onclick = () => {
alert("세번째클릭");
}
</script>
</body>
클래스의 내역중에 특정 id가 있다면 그걸 지우거나, 추가하고 있는지를 확인한다.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.red{
background-color: red;
/* 클래스가 레드인 놈에게 레드컬러를 준다. */
}
</style>
</head>
<body>
<h1 id="first">내용</h1>
<script>
const firstTag = document.querySelector("#first");
// 이렇게 사용하는것은 추천하지 않는다.
// css를 id나 class 등으로 컨트롤할 수 없을 경우에만 사용
// firstTag.style.color = "red";
firstTag.onclick = () =>{
// firsttag 클래스 중 red가 포함되어 있으면?
if(firstTag.classList.contains("red")){
// red를 클래스에서 제거
firstTag.classList.remove("red");
}else{
// red를 클래스에 추가
firsttag.classList.add("red");
}
}
</script>
</body>
즉 a.addeventlistner("click", (a()))는 클릭하면 a란 함수가 실행된다.
<body>
<h1 id="third">세번째</h1>
<h1 id="fourth">네번째</h1>
<script>
const third = document.querySelector('#third');
const fourth = document.querySelector("#fourth");
third.onclick = () => {
alert("세번째클릭");
}
fourth.addEventListener("click", ()=>{
alert("네번째클릭");
});
// 이벤트 리스너는 여러개가 달릴 수 있다
// fourth.addEventListener("click", ()=>{
// alert("네번째클릭2");
// });
// 이것은 위의 함수 버전이다.
const clickEvent = () =>{
alert("네번째클릭2");
}
fourth.addEventListener("click", clickEvent);
fourth.removeEventListener("click", clickEvent);
// 다시 말하지만 자판기에 동전을 넣으면 그 자판기 자체가 음료로 변하는것과 유사하다.
// 즉 퍼스트를 쿼리셀렉트로 얻은 순간 그 값으로 변하게 되니 그 뒤에 .을 붙여버려도 되는것.
document.querySelector('#first').addEventListener("click",()=>{
})
</script>
단, 이럴 경우엔 열자마자 실행된다.
<h1 id="first" onclick="alert('첫번째클릭')">첫번째</h1>
<h1 id="second" onclick="alert('두번째클릭')">두번째</h1>
<script>
// 화면에 키보드를 입력하면 h1에 입력한 key가 들어가도록 해보기
// 'keyup' 을 적어서 이용한다.
// 이렇겐 안된다.
// document.querySelector("#first").addEventListener(()=>{
// alert("키보드를 눌렀습니다.")
// })
// body를 붙이면 작동한다.
document.body.querySelector("#first").addEventListener(()=>{
alert("키보드를 눌렀습니다.")
})
</script>
f12으로 이벤트의 프로퍼티를 볼 수 있다.
<h1 id="first"></h1>
<script>
// 단축키 만들기 ctrl + i 를 사용하면 alert("aaaa") 창 출력, f12로 프로퍼티를 볼 수 있다.
document.body.addEventListener("keyup", (event)=>{
console.log(event);
if(event.ctrlKey && event.code === "KeyI"){
alert("ctrl + i");
}
});
</script>
<script>
//화면에 창을 띄우고 유저의 동의를 받을 때 사용.
//확인 true / 취소 false
while(true){
const result2 = prompt("가위/바위/보를 입력해주세요");
alert(result2);
}
// setTimeout, setInterval
// 정해놓은 시간이 지나면 내부 코드가 작동 된다
// 3초뒤에 메세지 띄어줘.
// 매개변수 - 콜백함수, 시간(ms) 로 이루어짐.
</script>
)) li - ul
<script>
// 문자열로 태그 안에 자식 태그 넣는 방법
// id가 list인 ul을 가져온다
const list = document.querySelector("#list");
// ul 안에 li를 넣는다
list.innerHTML = "<li>바나나 </li>";
// 바나나만이 아닌 사과랑 바나나 둘다 넣고 싶다?
// li를 innerHTML을 두번 작성하는건 안된다. 덮어 씌워지기 때문에.
list.innerHTML = `<li id="item1" style="color:red;">바나나 </li><li>사과 </li>`
</script>
<script>
//자바스크립트에서 태그를 만들어서 넣는 방법
const li1 = document.createElement("li");
li1.innerText = "바나나";
const li2 = document.createElement("li");
li2.innerHTML = "사과";
list.appendChild(li1);
list.appendChild(li2);
</script>
const 과일리스트 = ["멜론", "수박", "딸기"];
<script>
const 과일리스트 = ["멜론", "수박", "딸기"];
// 문제) 반복문과 createElement, appendChild를 이용해서 li추가
for (let i = 0; i < 과일리스트.length; i++) {
const tempLi = document.createElement("li");
tempLi = document.createElement("li");
tempLi.innerHTML = 과일리스트[i];
console.log(element);
}
</script>
foreach 로 해보는 문제.
<script>
const 과일리스트 = ["멜론", "수박", "딸기"];
// 문제2) 위에걸 foreach로 해보자. 복습: 배열의 각각 실행한다.
과일리스트.forEach((value)=>{
const tempLi = document.createElement("li");
list.appendChild(tempLi);
})
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 아래 adjust.. 와 관련된 각각 before, after-end가 어떻게 작동하는지에 대한 설명 -->
<!-- beforebegin -->
<ul id="list">
<!-- afterbegin -->
<!-- beforeend -->
</ul>
<!-- afterend -->
<script>
const 과일리스트 = ["멜론", "수박", "딸기"];
// innerAdjacentHTML
// 문자열로 태그를 만들어서 추가시킬 수 있다.
// 태그를 넣는 위치도 고를 수 있다.
//- beforebegin afterbegin beforeend afterend
list.insertAdjacentHTML(
"beforeend"
`<li>무화과</li>`
);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.light{
background-color:white;
}
.dark{
background-color:black;
}
</style>
</head>
<body>
<button id="themeButton">모드 변경</button>
<script>
// 변경 버튼을 누르면 body의 배경을 흰색 검은색 토글
// 새로고침해도 색깔이 유지되어야 한다. (스타일, 이벤트 리스너, 로컬 스토리지)
document.querySelector("#themeButton").addEventListener("click", ()=>{
if(document.body.classList.contains("dark")){
document.body.classList.remove("light");
document.body.classList.remove("dark");
document.body.classList.add("light");
localStorage.setItem("theme", "light");
}else{
document.body.classList.remove("light");
document.body.classList.remove("dark");
document.body.classList.add("dark");
localStorage.setItem("theme","dark");
}
})
const setBlackColor = () => {
if(localStorage.getItem("theme") === "dark"){
document.body.classList.add("dark");
}else{
document.body.classList.add("light");
}
}
</script>
</body>
</html>