JavaScript/문법

[JS 문법] 기초 CRUD(1)

마이구미+ 2023. 5. 10. 20:52

<변수>

- var

  • 같은 범위에서 재선언 하거나 업데이트 하는 것이 가능함
  • 코드의 다른 부분에서 이미 변수를 사용했는데 모르고 또 사용하는 경우 원하지 않는 결과값을 만들어낼 수 있음
  • 즉 버그의 발생 가능성이 높음

- let

  • {}(중괄호)라는 블록 범위에서만 사용함
  • 같은 범위 내에서 값을 업데이트 하는 것은 가능하지만 이미 선언한 변수를 재선언 하는 것은 불가능함
  • 다른 블록에서 같은 이름으로 선언해서 사용하는 것은 가능함
  • 변수명이 같아도 각기 다른 블록에 있다면 다른 변수로 취급됨

- const

  • 일정한 상수 값을 유지함
  • 선언된 블록 범위 내에서만 접근할 수 있으며, 업데이트도, 재선언도 불가능함
  • 범위 내에서는 변하지 않는 값이 됨

<Methods>

<!-- index.html -->
<!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">
    <link rel="stylesheet" href="index.css">
    <title>JS Practice</title>
</head>

<body>
    <h1>JS Practice</h1>
    <h1>두 번째 h1 태그</h1>
    <ul id="my-list">
        <li class="list-item">첫째내용</li>
        <li class="list-item">둘째내용</li>
        <li class="list-item">셋째내용</li>
    </ul>
    <script src="index.js"></script>
</body>

</html>
  • 위 html 파일을 기반으로 한다

- querySelector()

// index.js
const mainHeader = document.querySelector("h1")

 

콘솔로그에 mainHeader를 찍으면 이렇게 나온다


- querySelectorAll()

// index.js
const mainHeaders = document.querySelectorAll("h1")

콘솔로그에 mainHeaders를 찍으면 이렇게 나온다


- getElementById()

// index.js
const myList = document.getElementById("my-list")

콘솔로그에 myList를 찍으면 이렇게 나온다


- getElementsByClassName()

  • 공식문서: Document.getElementById() - Web API | MDN (mozilla.org)
  • 변수명 = document.getElementById("클래스명")
  • 해당하는 클래스를 가진 요소를 가져오는 메서드
  • 해당 클래스에 해당하는 요소가 여러 개 있을 수 있기 때문에 복수형으로 쓴다
  • HTML Collection으로 리스트 형태로 나온다
// index.js
const listItem = document.getElementsByClassName("list-item")

콘솔로그에 listItemdmf 찍으면 이렇게 나온다


- toggle()

  • 공식문서: DOMTokenList: toggle() method - Web APIs | MDN (mozilla.org)
  • 변수명.ClassList.toggle("클래스명")
  • 한 번 선언되면 변수에 담긴 태그 부분에 클래스명이 새로 생긴다
  • 두 번 선언되면 클래스명이 사라진다
  • 세 번 선언되면 다시 클래스명이 생긴다
  • 해당 클래스명의 css를 변경해 변화를 볼 수 있다
// index.js
const myList = document.getElementById("my-list")
console.log(myList)

myList.classList.toggle("mystyle")
/* index.css */
.mystyle {
    background-color: aqua;
}

콘솔로그에 myList를 찍었다

  • ul 태그에 class="mystyle"이 생긴 것을 확인할 수 있고
  • mystye 클래스에 css를 적용한대로 바뀐 것을 볼 수 있다
  • 여기서 toggle을 한 번 더 만들면 class 이름이 사라진다
// index.js
const myList = document.getElementById("my-list")
console.log(myList)

myList.classList.toggle("mystyle")
myList.classList.toggle("mystyle")

  • 한 번 더 toggle을 쓰면 또 다시 생긴다
  • 이렇게 변수에 아이디 태그가 담겨 있으면 바로 사용할 수 있지만 클래스 태그가 담긴 경우 HTML Collection 형식으로 되어 있기 때문에 토글 기능에 에러가 발생한다
// index.js
const listItem = document.getElementsByClassName("list-item")
console.log(listItem)
listItem.classList.toggle("mystyle2")

  • 어디서 에러가 발생했는지 확인하기 위해 앞뒤로 콘솔로그를 찍어보자
// index.js
const listItem = document.getElementsByClassName("list-item")
console.log(listItem)
console.log("문제가 있나요?")
listItem.classList.toggle("mystyle2")
console.log("문제가 해결되었다!")

맨 아래 콘솔로그가 안 찍힌 걸로 보아 listItem.classList.toggle("mystyle2") 부분이 문제라는 것을 알 수 있다

  • 리스트를 forEach문으로 돌려서 요소 하나하나 꺼내면서 toggle 기능을 불러줘야 한다
// index.js
const listItem = document.getElementsByClassName("list-item")
console.log(listItem)

Array.from(listItem).forEach(element => {
    console.log(element)
    element.classList.toggle("mystyle2")
})
  • Array는 HTMLCollection 형태이니 listItem을 Array 형태로 바꿔주고 있다
  • 거기에 forEach문을 돌리는데 python 문법으로 비교하면 for num in numbers 할 때 num, 즉 요소 하나하나를 element에 담는 것 같다

  • 이제 HTML 안에 있던 요소들이 하나씩 나온 것을 볼 수 있고 class 이름에 mystyle2가 추가된 것을 확인할 수 있다
/* index.css */
.mystyle2 {
    background-color: greenyellow;
}
  • css 적용한대로 잘 바뀐 것을 볼 수 있다
  • 이것도 위에랑 똑같이 바로 아래에 toggle을 한 번 더 쓰면 사라지고 3번째 쓰면 다시 생긴다

<Events>

- onclick()

<!-- index.html -->
<html>
...
<body>
    ...
    <button onclick="handleClick()">버튼</button>
    <script src="index.js"></script>
</body>
</html>
  • body 태그 안쪽에 아무데나 버튼을 만든다
  • button 태그에 onclick="함수명()"을 작성한다
  • 이제 js 파일로 가서 해당 함수를 작성하자!
// index.js
function handleClick() {
    console.log("handleClick함수 실행 중")
}
  • 백엔드의 기초! 함수를 짜기 전에 해당 함수가 정말 클릭했을 때 실행이 되는지 콘솔로그를 찍어본다!

콘솔로그가 잘 찍힌다 5번 눌렀더니 옆에 숫자 5가 생겼다 누를 때마다 숫자가 올라간다

  • 이제 handleClick() 함수에 위에서 작성한 토글 기능을 넣어보자
// index.js
function handleClick() {
    console.log("handleClick함수 실행 중")
    myList.classList.toggle("mystyle")
    Array.from(listItem).forEach(element => {
        console.log(element)
        element.classList.toggle("mystyle2")
    })
}
  • LiveServer로 가서 확인해보자

버튼 누르기 전
1번 눌렀을 때 토글 on
2번 눌렀을 때 토글 off
3번 눌렀을 때 토글 on


- onclick this

  • li 태그들 각각을 클릭했을 때 뭔가 함수가 실행되게 하고 싶다
  • 먼저 html에서 li태그에 각각 id값과 onclick 이벤트를 추가한다
<!-- index.html -->
...
        <li class="list-item" id="first-item" onclick="handleSingleClick(this)">첫째내용</li>
        <li class="list-item" id="second-item" onclick="handleSingleClick(this)">둘째내용</li>
        <li class="list-item" id="third-item" onclick="handleSingleClick(this)">셋째내용</li>
...
  • 매개변수 this는 해당 li 태그를 가리킨다
  • js로 가서 handleSingleClick 함수를 만들자
// index.js
function handleSingleClick(e) {
    console.log("single click!")
    console.log(e)
}
  • e에는 this, 즉 li태그 각각이 담긴다
  • 콘솔로그를 찍어보자

  • 각각 li 들을 클릭하면 우측에 콘솔로그가 찍히는 것을 확인할 수 있다

<Properties>

- id

  • 공식문서: HTML DOM Element id Property (w3schools.com)
  • 위에 li태그의 handleSingleClick() 함수 부분에서 html에서 불러온 id값이 나오게 하고 싶으면 html 파일에 this를 this.id로 바꾸면 된다
<!-- index.html -->
...
        <li class="list-item" id="first-item" onclick="handleSingleClick(this.id)">첫째내용</li>
        <li class="list-item" id="second-item" onclick="handleSingleClick(this)">둘째내용</li>
...

  • 첫째내용을 클릭하면 해당 li태그의 id값인 first-item이 찍힌다
// index.js
...
    console.log(e.id)
...
  • js에서 e.id를 해도 id값이 찍힌다

  • 단 html에서 this.id를 하고 js에서 e.id를 또 하면 <해당 li 태그>.id.id가 되는 거라 undefined가 찍힌다
  • html이든 js든 한 군데에서만 딱 골라서 해줘야 한다
// index.js
function handleSingleClick(e) {
    console.log("single click!")
    console.log(e.innerText)
    const singleItem = document.getElementById(e.id)
    singleItem.classList.toggle("mystyle")
}
  • 함수를 이렇게 수정해주면 li 태그 각각을 클릭했을 때 li 태그 부분만 css가 변하는 것을 확인할 수 있다

  • 둘째내용은 1번만 클릭해서 토글 on 되어 배경색이 변했고, 첫째내용은 2번 클릭해서 토글이 off 돼서 배경색이 원래대로 돌아왔다

- innerText

// index.js
function handleSingleClick(e) {
    ...
    console.log(e.innerText)
}

html 파일의 li 태그에 담긴 내용이 콘솔로그에 찍힌다