본문 바로가기
학원에서 배운 것/JavaScript

KDT 5th 웹개발자 입문 수업 14일차

by 쿠리의일상 2023. 2. 14.

1. Array 메서드 체이닝

1-1. .split(구분자)

구분자를 기준으로 문자열을 나눈다. 나눠진 문자열들이 배열로 리턴된다.

let str = "Hello";
let strArr = str.split('');
console.log(strArr); //[ 'H', 'e', 'l', 'l', 'o' ]

구분자를 '' 문자열 없이 사용해주면, 문자 하나하나가 모두 나눠진다.

 

1-2. .join(구분자)

구분자를 기준으로 배열을 구분자와 문자열로 합쳐준다. 문자열 사이사이 구분자가 들어간 채로 배열로 리턴된다.

let arr = [ 'H', 'e', 'l', 'l', 'o' ];
let str = arr.join('');
console.log(str); //Hello

구분자를 '' 문자열 없이 사용해주면 배열에 들은 문자들이 구분자가 따로 없이 문자열로 합쳐진다.

 

1-3. .reverse()

배열의 순서를 반대로 반전시키고 그 배열을 리턴한다.

 

 

1-4. 배열의 메서드들의 메서드 체이닝

let helloTest = "H-e-l-l-o";
let finalStr = helloTest.split('-').reverse().join('');
console.log(finalStr);
  • 각각의 메서드를 연결하여 사용하는 개념
  • 메서드들의 리턴값이 배열 자체여야 가능하다.
const obj = {
  arr : ['a', 'b', 'c', 'd'],
  number : 10,
}

let testStr = obj.arr.reverse().join('');
console.log(testStr);
let testStr2 = obj.number.reverse().join('');
console.log(testStr2); //TypeError
let testStr3 = obj.str.reverse().join('');
console.log(testStr2); //TypeError

 


값이 있을지 없을지 모를 때, 디버깅 확인용으로 ?를 사용해주면 undefined가 나올 것 같은 객체에 에러가 안나게 해줄 수 있다.

예를 들어 객체의 키를 사용할 때 없을지 있을지 모를 때, 키의 뒤에 ?를 추가하여,

let testStr3 = obj.str?.reverse().join('');
console.log(testStr3); //undefined

그러면 에러가 나지 않고 undefined 처리만 된다.

물론 이 방식은 try-catch 문을 사용해주는 것이 올바르다.


 

 

2. DOM (Document Object Model)

HTML 문서 요소의 집합으로, HTML 문서는 각각의 node와 object의 집합으로 문서를 표현해준다.

 

그래서 각각의 node/object에 접근하여 문서 구조, 스타일, 내용 등을 변경할 수 있도록 자바스크립트를 활용해주는 것

2-1. DOM API

기본적으로 최상위 객체인 document의 내장 메서드에 접근하는 개념이다.

 

2-1-1. querySelector('요소선택자')

요소 선택자를 사용하여 자신이 가져오고 싶어하는 요소를 가져오는 메서드

문서에서 만나는 제일 첫번째 요소를 반환

let boxEl = document.querySelector('.box');
console.log(boxEl);

let boxEl2 = document.querySelector('#box2');
console.log(boxEl2);

let listEl = document.querySelector('ul>li:nth-child(2)');
console.log(listEl);

 

2-1-2. getElementById('id명')

id명으로 불러서 해당 요소를 불러오는 메서드 (id값만 들어가므로 #이 필요 없음)

let boxEl3 = document.getElementById('third');
console.log(boxEl3);

 

 

3. classList

선택 요소의 class를 활용해줄 수 있는 리스트

 

3-1. classList.add('클래스명') : class 추가

 

3-2. classList.remove('클래스명') : class 제거

 

3-3. classList.contain('클래스명') : class 존재하는지 체크, boolean 리턴

const boxEl = document.querySelector('.box');
boxEl.classList.add('orange');

const thirdBoxEl = document.getElementById('third');
thirdBoxEl.classList.remove('box');

console.log(boxEl.classList.contains('box')); //true
console.log(thirdBoxEl.classList.contains('box')); //false

 

//orange 클래스를 가진 첫번째 Element
let orangeEl = document.querySelector('.orange');

//skyblue 아이디를 가진 Element
let skyblueElId = document.getElementById('skyblue');

//ul 리스트의 li 중 2번째 자식 요소
let secondLi = document.querySelector('ul>li:nth-child(2)');

//orange 클래스 추가
secondLi.classList.add('orange');
console.log(orangeEl, skyblueElId, secondLi);

//orange 클래스가 있다면, 지워라
if(orangeEl.classList.contains('orange') === true) {
  orangeEl.classList.remove('orange');
}

console.log(orangeEl);

 

 

4. setAttribute

선택한 요소의 속성값을 직접 지정할 수 있는 메서드

요소.setAttribute('속성명', '속성값');

여러 속성값을 나타내고 싶다면 css 입력과 동일하게 ; 으로 구분해서 한번에 입력해줄 것

setAttribute는 쌓이는 개념이 아니라 통째로 바뀌는 개념이므로 덮어쓰여진다.

const boxEl = document.querySelector('.box');
const inputEl = document.querySelector('input');

boxEl.setAttribute('style', 'background-color:orange'); //적용 안됨
boxEl.setAttribute('style', 'height: 300px; background-color:blue'); //적용 됨
inputEl.setAttribute('placeholder', '통합검색');

 

 

5. textContent

요소 안의 텍스트 내용을 get(읽어)하거나 set(변경) 할 수 있음

요소.textContent

6. innerHTML / innerText

요소.innerHTML 은 < > 같은 태그를 읽어와서 html화 할 수 있지만

요소.innerText는 textContent와 동일, 텍스트로만 읽어오거나 수정할 수 있음

const divOneEl = document.querySelector('.div1');
const divTwoEl = document.querySelector('.div2');

divOneEl.innerHTML = '<button>Click!</button>';
divTwoEl.innerText = '<button>Click!</button>';

<body>
  <div class="box1">1</div>
  <div class="box2">2</div>
  <input type="text"/>
</body>

<script>
  const boxEl_1 = document.querySelector('.box1');
  const boxEl_2 = document.querySelector('.box2');
  const inputEl = document.querySelector('input');

  boxEl_1.innerHTML = '<a href="#">네이버로 이동</a>';
  boxEl_2.innerHTML = `박스 내용 및 스타일 변경`;
  // boxEl_2.setAttribute('style', 'background-color: orange;');
  boxEl_2.style = 'background-color : orange';
  inputEl.setAttribute('placeholder', '아이디를 입력하세요');
</script>

요소.style 프로퍼티로 스타일 속성값을 직접 지정해줄 수 있다.

 

 

7. createElement

html DOM을 만들어내는 메서드

createElement('요소명')

 

 

8. append / appendChild

특정 DOM 요소에 다른 요소를 맨 뒤에 자식으로 추가하는 메서드

 

DOM요소.append(추가할 내용)

반환 값은 따로 없지만 Node나 컨텐츠 텍스트를 추가할 수 있고, 여러 가지 값을 한번에 붙일 수 있다.

 

DOM요소.appendChild(추가할 요소)

Node만 추가할 수 있으며 한번에 하나만 추가할 수 있지만 추가한 Node를 반환한다.

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<script>
    const li = document.createElement('li');
    li.textContent = 'test';

    const ulEl = document.querySelector('ul');
    ulEl.appendChild(li);
    ulEl.append('내용');
</script>

 

9. prepend(추가할요소)

prependChild는 없음

append와 반대로 부모 노드의 첫번째 요소로 추가

 

10. DOM요소.remove()

선택한 DOM요소를 삭제하는 메서드

const classLi = document.querySelector('.list');
classLi.remove();

 

11. parentNode

특정 DOM 요소의 직계 부모 노드를 가져와서 확인하는 프로퍼티

DOM요소.parentNode

 

12. childNodes

특정 DOM 요소의 자식 요소를 전부 확인하는 프로퍼티

DOM요소.childNodes

컨텐츠 내용과 자식 요소들이 배열 형태로 출력된다.

 

13. children

특정 DOM 요소의 자식 노드만을 확인하는 프로퍼티

DOM요소.children

    const ulEl = document.querySelector('ul');
    console.log(ulEl.childNodes);
    console.log(ulEl.children);

 

14. onclick

각각의 HTML 요소에 속성값으로 js 함수를 연결하는 속성

<body>
  <div class="box1" onclick="test()">1</div>
  <div class="box2" onclick="changeColor()">2</div>
</body>
<script>
  function test() {
    alert('test');
  }
  function changeColor() {
    const boxEl = document.querySelector('.box2');
    boxEl.setAttribute('style', 'background-color : orange;');
  }
</script>

 

 

15. addEventListener(이벤트, 콜백함수)

선택 요소에 지정한 이벤트가 발생하면 명령어를 실행시키는 메서드

<body>
  <div class="add">3</div>
</body>
<script>
  const box_3 = document.querySelector('.add');
  box_3.addEventListener('click', function() {
    alert('box3');
  })
</script>

 

15-1. 이벤트의 종류

15-1-1. click :클릭

 

15-1-2. mouse 계열

15-1-2-1. mouseover : 요소에 커서를 올렸을 때

15-1-2-2. mouseout : 마우스가 요소를 벗어날 때

15-1-2-3. mousedown : 마우스 버튼을 누르고 있는 상태

15-1-2-4. mouseup : 마우스 버튼을 떼는 순간

 

15-1-3. focus : 포커스가 갔을 때

15-1-4. blur : 포커스가 벗어나는 순간

 

15-1-5. key 계열

15-1-5-1. keypress : 키를 누르는 순간, 누르고 있는 동안 계속

15-1-5-2. keydown : 키를 누르는 순간만

15-1-5-3. keyup : 키를 눌렀다가 떼는 순간

 

15-1-6. load : 웹 페이지에 필요한 모든 파일의 다운로드가 완료되었을 때

15-1-6-. unload : 링크를 타고 이동하거나 브라우저를 닫을 때

 

15-1-7. resize : 브라우저 창의 크기가 변경될 때

 

15-1-8. scroll : 스크롤이 발생할 때

 

15-1-9. change : 폼 필드의 상태가 변경되었을 때

 

 

박스를 클릭하면 색이 바뀌는 요소 만들기

  <style>
    div {
      width: 100px;
      height: 100px;
    }
    .orange {
      background-color: orange;
    }
    .skyblue {
      background-color: skyblue;
    }
  </style>

<body>
  <div class="box1">box1</div>
  <div class="box2" onclick="boxClick(this)">box2</div>
</body>
<script>
  const box_1 = document.querySelector('.box1');
  //const box_2 = document.querySelector('.box2');

  box_1.addEventListener('click', function() {
    if(this.classList.contains('orange') === false) {
      this.classList.remove('skyblue');
      this.classList.add('orange');
    } else {
      this.classList.remove('orange');
      this.classList.add('skyblue');
    }
  });

  function boxClick(element) {
    if(element.classList.contains('orange') === false) {
      element.classList.remove('skyblue');
      element.classList.add('orange');
    } else {
      element.classList.remove('orange');
      element.classList.add('skyblue');
    }
  }
</script>

addEventListener() 의 콜백함수에선 this를 사용하여 해당 이벤트가 발생하는 객체를 가져올 수 있고

onclick 속성의 경우, 따로 매개변수를 this로 받아와줘서 자기 자신의 객체를 함수 안에 가져올 수 있다.

 

 

16. querySelectorAll('요소선택자')

모든 요소를 가져와서 배열로 리턴해준다.

 

17. forEach( function(반복중인요소, 인덱스) { } )

찾은 요소 전부에게 반복적으로 실행하게 해주는 메서드

<body>
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
  <div class="box">7</div>
  <div class="box">8</div>
  <div class="box">9</div>
  <div class="box">10</div>
</body>
<script>
  const boxEls = document.querySelectorAll('.box');

  boxEls.forEach(function(boxEl, idx) {
    console.log(boxEl, idx);
  });
</script>

 

 

18. this / e.target

DOM요소에서 this를 사용하면, this는 자기 자신의 node를 가리킨다. (onclick에서 주로 사용)

<body>
  <ul>
    <li onclick="deleteThis(this)">1</li>
    <li onclick="deleteThis(this)">2</li>
    <li onclick="deleteThis(this)">3</li>
    <li onclick="deleteThis(this)">4</li>
  </ul>
</body>
<script>

  function showThis(e) {
    console.log(e);
  }
  function deleteThis(e) {
  // 가져와지는 e 자체가 해당 DOM요소이므로 remove()에 접근이 가능
    e.remove();
  }
</script>

 

e.target (이벤트 객체) -> addEventListener 에서 주로 사용

Document에서 발생하는 이벤트는 이벤트 객체 e를 통해 확인 가능

<body>
  <ul>
    <li class="list">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
  </ul>
</body>
<script>
  const listEl = document.querySelector('.list');
  listEl.addEventListener('click', function(e) {
    e.target.remove();
  });
</script>

 

 

19. defer / async

script에 넣어주는 속성

일반적인 script는 html 파싱과 무관하게 스크립트의 순서상 js파일 읽히게 되어 html 파싱이 중단되어 DOM 생성이 중단되는 문제가 있다. (순서가 중요)

 

async를 추가해주면 html 파싱과 외부 자바스크립트 파일의 로드가 비동기적으로 동시에 진행되고, js 파싱과 실행은 js파일의 로드가 완료된 직후 바로 진행되어 html 파싱이 중단되어 문제가 발생할 가능성이 있다.

 

defer의 경우 html 파싱과 js파일의 로드가 비동기적으로 진행됨은 async과 동일하지만 js파싱과 실행은 html 파싱이 완료된 직후(DOM 생성이 완료된 직후) js가 실행된다. ---> defer가 생긴 이후로 가독성을 위하여 html <head> 안에 script를 두기 시작했다고 한다.

 

 

 

20. todo 리스트 만들기

const todoInputField = document.querySelector('.input-task');
const todoSendBtn = document.querySelector('.input-btn');
const todoUlist = document.querySelector('.todo-list');

todoSendBtn.addEventListener('click', function() {
  if(todoInputField.value === "") {
    todoInputField.setAttribute('placeholder', '내용을 입력하세요!');
    return;
  }

  const todoLiEl = document.createElement('li');
  const todoCheckbox = document.createElement('input');
  const todoContent = document.createElement('span');
  const todoButton = document.createElement('button');

  todoCheckbox.setAttribute('type', 'checkbox');
  todoCheckbox.onclick = function(e) {
    if(todoCheckbox.checked === true) {
      todoContent.setAttribute('style', 'text-decoration: line-through');
    }
  }
  todoButton.innerHTML = '삭제';
  todoButton.onclick = function(e) {
    e.target.parentNode.remove();
  };  

  //입력된 값 넣어주기
  todoContent.innerText = (todoInputField.value);
  
  //리스트에 내용 추가
  todoLiEl.appendChild(todoCheckbox);
  todoLiEl.appendChild(todoContent);
  todoLiEl.appendChild(todoButton);

  //최종 리스트 추가
  todoUlist.appendChild(todoLiEl);

  //인풋필드 초기화
  todoInputField.value = "";
  todoInputField.focus();
});

배운 것을 가지고 todo 리스트를 만들었다. 힘듦..