본문 바로가기
Today I Learned/SeSAC 웹 2기

[새싹x코딩온] jQuery와 vanillaJS 비교해보기

by suyeonnie 2024. 11. 16.

jQueyr는 요즘 많이 안 쓰인다고는 하지만, 그래도 어떻게 쓰는 지 사용법을 알아두면 좋다고 해서 과제를 다시 풀어보는 김에 vanillaJS로 다시 풀어봤다. jQuery는 수업 내용을 많이 잊어버려서 더 헤맸다. ^^... 현업에서 많이 쓰인다는 다른 JavaScript 라이브러리들이 궁금해지는 밤이다 🌝
 
자, 일단 오늘은 오늘의 복습을 하자. 

  • jQuery 개념
  • 과제1: 과일 사진 변경 버튼
  • 과제2: 상자 색 변경
     

📌 개념

jQuery는 DOM을 조작하고 UI이벤트를 다루기 위한 라이브러리이다.
 
요소를 선택할 때 vanillaJS 처럼 Document 어쩌구 저쩌구를 다 쓸 필요없이 `$('css선택자').동작함수()`를 써주면 된다. 아닛...? 너무 간단하잖아? `$('button').css('color', 'red')`와 같이 모든 버튼의 색깔을 한번에 바꿀 수도 있다.
 

function submitjs() {
  //<div id='div1'></div>
  document.getElementById('div1').innerText = '반갑습니다!!';
  document
    .getElementById('div1')
    .setAttribute('style', 'border: 2px solid red');
}
function submitjq() {
  $('#div1').text('hello jQuery');
  $('#div1').css('border', '3px dotted blue');
}

 
함수 이름에서 알수 있듯이 같은 동작을 수행하는데, vanillaJS로 3줄이 넘어가는 걸 2줄로 작성할 수 있다...! 
 

📌 과제1 : 과일 사진 변경 버튼

이벤트 핸들러는 인라인으로 설정된 상태에서,

<img src="../img/q.jpg" alt="과일" width="230px" height="200px" />
    <br />
<button onclick="changeImg('apple')">사과</button>
<button onclick="changeImg('banana')">바나나</button>
<button onclick="changeImg('grape')">포도</button>
<button onclick="changeImg('peach')">복숭아</button>

 
노가다로 jQuery를 작성했다. 동작하는 데 의의를 두었다.

//jQUery
  function changeImg(name) {
    if (name === 'apple') {
      $('img').attr('src', '../img/apple.jpg');
    } else if (name === 'banana') {
      $('img').attr('src', '../img/banana.jpg');
    } else if (name === 'grape') {
      $('img').attr('src', '../img/grape.jpg');
    } else if (name === 'peach') {
      $('img').attr('src', '../img/peach.jpg');
    }
  }

 
모범 해답을 봤다. 충격적으로 간단하다. 왜 이걸 생각 못했지??????
 
템플릿 리터럴을 사용해서 매개변수로 받아온 이름에 따라 경로가 바뀌도록 해준다.
jQuery에서 `$(선택자).attr('속성', '속성값');`은 속성을 변경해준다.

//jQuery
      function changeImg(name) {
        $('img').attr('src', `../img/${name}.jpg`);
      }

 
이번에는 jQuery CDN을 주석처리하고, vanillaJS로 작성했다.

//vanillaJS
  const changeImg = (name) => {
    const img = document.querySelector('img');
    img.src = `../img/${name}.jpg`;
  };

 
 

📌 과제2:  상자 색 변경

jQuery 2가지 방법이 있다. JDN UI CDN을 추가해서 `switchClass`로 푸는 방법과 배열을 활용하는 방법이다.
 
첫번째 방법은 클래스를 조작하는 함수 `hasClass`의 return값을 활용해서 조건문을 썼다.
`$('css 선택자').switchClass('클래스명1', '클래스명2', 시간)`은 클래스1을 클래스2로 바꾼다.

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];

      // TODO2: changeColor 함수 내부 작성
      function changeColor() {
        // console.log($('div'));

        //방법1: switchClass
        if ($('div').hasClass('red')) {
          $('div').switchClass('red', 'orange');
        } else if ($('div').hasClass('orange')) {
          $('div').switchClass('orange', 'yellow');
        } else if ($('div').hasClass('yellow')) {
          $('div').switchClass('yellow', 'green');
        } else if ($('div').hasClass('green')) {
          $('div').switchClass('green', 'blue');
        } else if ($('div').hasClass('blue')) {
          $('div').switchClass('blue', 'orange');
        }

        //방법2: 배열 활용
        let nowClass = $('div').attr('class'); // 현재 클래스 값 가져오기
        let i = colors.indexOf(nowClass); // 현재 클래스의 인덱스 찾기
        //마지막 색상에서 처음으로 순환
        if (i == colors.length - 1) $('div').switchClass(nowClass, colors[0]);
        //현재 색상이 마지막이 아니라면 다음 색상으로 이동
        else $('div').switchClass(nowClass, colors[i + 1]); 
      }

 
두번째 방법은  `$('css선택자').attr('속성', '속성값');`으로 현재 클래스 값을 담는 `nowClass` 변수를 만들고, 현재 클래스의 인덱스값을 담는 변수 `i`를 만들었다. 참고로 indexOf()는 배열에서 동일한 요소가 여러 개 있으면 첫번째 발견된 위치의 인덱스만 반환한다. 현재 색상 배열에는 중복되는 이름이 없으므로 안전하게 사용한다. 👷🏻‍♀️ 
 
다음으로 현재 클래스가 마지막 색상(purple)이라면 배열의 첫번째 색상(red)로 클래스를 바꿔주는 조건문을 작성해서 색상이 바뀌게 해준다. 아래는 위와 동일한 로직으로 vanillaJS로 작성한 코드이다.

//방법4: vanillaJS
    const div = document.querySelector('div');
    console.log(div);

    const nowClass = div.className; //현재 클래스 가져오기
    const i = colors.indexOf(nowClass); //현재 클래스의 인덱스 가져오기

    //마지막 색상이면 첫 번째 색상으로 순환
    if (i === colors.length - 1) {
      div.classList.remove(nowClass);
      div.classList.add(colors[0]);
    } else {
      //다음 색상으로 변경
      div.classList.remove(nowClass);
      div.classList.add(colors[i + 1]);
    }