분류 javascript

jQuery에서 바닐라 JavaScript로 이동하기 위한 치트 시트

컨텐츠 정보

  • 조회 268 (작성일 )

본문

jQuery는 여전히 유용하고 실용적인 라이브러리이지만 프로젝트에서 쿼리를 사용하여 요소 선택, 스타일 지정, 애니메이션 및 데이터 가져 오기와 같은 기본 작업을 수행하는 데 의존하지 않을 가능성이 점점 커지고 있습니다. ES6에 대한 광범위한 브라우저 지원 (작성 당시 96% 이상)이 이제는 jQuery에서 벗어날 수 있는 좋은 시기입니다.


https://tobiasahlin.com/blog/move-from-jquery-to-vanilla-javascript/ 


최근 에이 블로그에서 jQuery를 제거하고 몇 가지 패턴에 대해 반복해서 검색했습니다. 

시간을 절약하기 위해 이 실용적인 참조 가이드를 가장 일반적인 jQuery 패턴과 이에 상응하는 JavaScript로 컴파일했습니다. 다음 개념 및 기능에서 바닐라 JavaScript로 이동하는 방법을 다룹니다.


Selecting elementsEvents.css()Document readyClasses.ajax()Creating elementsHTML & text


요소 선택 (Selecting elements) 


무언가를 하기 위해 하나 또는 여러 개의 DOM 요소를 선택하는 것은 jQuery의 가장 기본적인 요소 중 하나입니다. JavaScript에서 $() 또는 jQuery()와 동등한 것은 querySelector() 또는 querySelectorAll()이며, 이는 jQuery와 마찬가지로 CSS 선택기로 호출 할 수 있습니다.


// jQuery, select all instances of .box
$(".box");

// Instead, select the first instance of .box
document.querySelector(".box");

// …or select all instances of .box  
document.querySelectorAll(".box");


선택의 모든 요소에서 함수 실행 


querySelectorAll()은 jQuery와 마찬가지로 작업 할 수 있는 요소의 배열을 반환합니다. 그러나 jQuery 객체에서 단순히 호출하여 전체 선택에 대해 jQuery로 함수를 실행할 수 있지만 JavaScript를 사용하여 요소 배열을 반복해야 합니다.


// with jQuery
// Hide all instances of .box
$(".box").hide();

// Without jQuery
// Loop over the array of elements to hide all instances of .box
document.querySelectorAll(".box").forEach(box => { box.style.display = "none" }


다른 요소에서 하나의 요소 찾기 


일반적인 jQuery 패턴은 .find()를 사용하여 다른 요소 내에서 요소를 선택하는 것입니다. 요소에서 querySelector 또는 querySelectorAll을 호출하여 요소의 하위 항목에 대한 선택 범위를 지정하면 동일한 효과를 얻을 수 있습니다.


// With jQuery
// Select the first instance of .box within .container
var container = $(".container");
// Later...
container.find(".box");

// Without jQuery
// Select the first instance of .box within .container
var container = document.querySelector(".container");
// Later...
container.querySelector(".box");


parent(), next() 및 prev()를 사용하여 트리 탐색 


다른 요소를 기준으로 하위 요소 또는 상위 요소를 선택하기 위해 DOM을 탐색하려는 경우 해당 요소의 nextElementSibling, previousElementSibling 및 parentElement를 통해 액세스 할 수 있습니다.


// with jQuery
// Return the next, previous, and parent element of .box
$(".box").next();
$(".box").prev();
$(".box").parent();

// Without jQuery
// Return the next, previous, and parent element of .box
var box = document.querySelector(".box");
box.nextElementSibling;
box.previousElementSibling;
box.parentElement;


이벤트 작업 


jQuery에서 이벤트를 청취하는 방법은 다양하지만 .on(), .bind(), .live 또는 .click()을 사용하든 JavaScript와 동등한 .addEventListener를 사용하면 됩니다.


// With jQuery
$(".button").click(function(e) { /* handle click event */ });
$(".button").mouseenter(function(e) {  /* handle click event */ });
$(document).keyup(function(e) {  /* handle key up event */  });

// Without jQuery
document.querySelector(".button").addEventListener("click", (e) => { /* ... */ });
document.querySelector(".button").addEventListener("mouseenter", (e) => { /* ... */ });
document.addEventListener("keyup", (e) => { /* ... */ });


동적으로 추가 된 요소의 이벤트 청취 


jQuery의 .on() 메소드를 사용하면 DOM에 동적으로 추가되는 객체의 이벤트를 듣는 "실시간"이벤트 핸들러로 작업 할 수 있습니다. jQuery없이 유사한 것을 달성하기 위해 DOM에 추가 할 때 요소에 이벤트 핸들러를 첨부 할 수 있습니다.


// With jQuery
// Handle click events .search-result elements, 
// even when they're added to the DOM programmatically
$(".search-container").on("click", ".search-result", handleClick);

// Without jQuery
// Create and add an element to the DOM
var searchElement = document.createElement("div");
document.querySelector(".search-container").appendChild(searchElement);
// Add an event listener to the element
searchElement.addEventListener("click", handleClick);


이벤트 트리거 및 생성 


dispatchEvent()를 호출하여 trigger()로 이벤트를 수동으로 트리거 하는 것과 같습니다. dispatchEvent() 메소드는 모든 요소에서 호출 할 수 있으며 Event를 첫 번째 인수로 사용합니다.


// With jQuery
// Trigger myEvent on document and .box
$(document).trigger("myEvent");
$(".box").trigger("myEvent");

// Without jQuery
// Create and dispatch myEvent
document.dispatchEvent(new Event("myEvent"));
document.querySelector(".box").dispatchEvent(new Event("myEvent"));


스타일링 요소 


jQuery로 인라인 CSS를 변경하기 위해 요소에서 .css()를 호출하는 경우 JavaScript에서 .style을 사용하고 동일한 속성을 얻기 위해 다른 속성에 값을 할당합니다.


// With jQuery
// Select .box and change text color to #000
$(".box").css("color", "#000");

// Without jQuery
// Select the first .box and change its text color to #000
document.querySelector(".box").style.color = "#000";


jQuery를 사용하면 키-값 쌍이 있는 객체를 전달하여 한 번에 많은 속성의 스타일을 지정할 수 있습니다. JavaScript에서는 한 번에 하나씩 값을 설정하거나 전체 스타일 문자열을 설정할 수 있습니다.


// With jQuery
// Pass multiple styles
$(".box").css({
  "color": "#000",
  "background-color": "red"
});

// Without jQuery
// Set color to #000 and background to red
var box = document.querySelector(".box");
box.style.color = "#000";
box.style.backgroundColor = "red";

// Set all styles at once (and override any existing styles)
box.style.cssText = "color: #000; background-color: red";


hide() 및 show() 


.hide() 및 .show() 편의 메서드는 .style 속성에 액세스하고 display를 none 및 block으로 설정하는 것과 같습니다.


// With jQuery
// Hide and show and element
$(".box").hide();
$(".box").show();

// Without jQuery
// Hide and show an element by changing "display" to block and none
document.querySelector(".box").style.display = "none";
document.querySelector(".box").style.display = "block";


Document ready 


예를 들어 DOM이 완전히 로드 될 때까지 기다려야 하는 경우 DOM의 객체에 이벤트를 첨부 할 때는 일반적으로 jQuery에서 $(document) .ready() 또는 일반적인 속기 $()를 사용합니다. DOMContentLoaded를 들으면서 비슷한 함수를 쉽게 대체 할 수 있습니다 


// With jQuery
$(document).ready(function() { 
  /* Do things after DOM has fully loaded */
});

// Without jQuery
// Define a convenience method and use it
var ready = (callback) => {
  if (document.readyState != "loading") callback();
  else document.addEventListener("DOMContentLoaded", callback);
}

ready(() => { 
  /* Do things after DOM has fully loaded */ 
});


class 작업 


classList 속성을 통해 클래스에 쉽게 액세스하고 클래스를 사용하여 클래스를 토글, 교체, 추가 및 제거 할 수 있습니다.


// With jQuery
// Add, remove, and the toggle the "focus" class
$(".box").addClass("focus");
$(".box").removeClass("focus");
$(".box").toggleClass("focus");

// Without jQuery
// Add, remove, and the toggle the "focus" class
var box = document.querySelector(".box");
box.classList.add("focus");
box.classList.remove("focus");
box.classList.toggle("focus");



여러 클래스를 제거하거나 추가하려면 .add() 및 .remove()에 여러 인수를 전달하면 됩니다.


// Add "focus" and "highlighted" classes, and then remove them
var box = document.querySelector(".box");
box.classList.add("focus", "highlighted");
box.classList.remove("focus", "highlighted");


상호 배타적인 두 클래스를 토글 하는 경우 classList 속성에 액세스하고 .replace()를 호출하여 한 클래스를 다른 클래스로 바꿀 수 있습니다.


// Remove the "focus" class and add "blurred"
document.querySelector(".box").classList.replace("focus", "blurred");


요소에 클래스가 있는지 확인 


요소에 특정 클래스가 있는지 여부에 따라 함수를 실행하려는 경우 jQuery의 .hasClass()를 .classList.contains()로 바꿀 수 있습니다.


// With jQuery
// Check if .box has a class of "focus", and do something
if ($(".box").hasClass("focus")) {
  // Do something...
}

// Without jQuery
// Check if .box has a class of "focus", and do something
if (document.querySelector(".box").classList.contains("focus")) {
  // Do something...
}


.get() 또는 .ajax()를 사용한 네트워크 요청 


feth()를 사용하면 jQuery의 ajax() 및 get() 메소드와 유사한 방식으로 네트워크 요청을 작성할 수 있습니다. fetch ()는 URL을 인수로 사용하여 응답을 처리하는 데 사용할 수 있는 약속을 반환합니다.


// With jQuery
$.ajax({
    url: "data.json"
  }).done(function(data) {
    // ...
  }).fail(function() {
    // Handle error
  });

// Without jQuery
fetch("data.json")
  .then(data => {
    // Handle data
  }).catch(error => {
    // Handle error
  });


요소 만들기 


JavaScript에 요소를 동적으로 작성하여 DOM에 추가하려는 경우 문서에서 createElement()를 호출하고 작성할 요소를 표시하는 태그 이름을 전달할 수 있습니다.


// Create a div & span
$("<div/>");
$("<span/>");

// Create a div and a span
document.createElement("div");
document.createElement("span");


해당 요소에 내용을 추가하려면 textContent 속성을 설정하거나 createTextNode를 사용하여 텍스트 노드를 만들어 요소에 추가하면 됩니다.


var element = document.createElement("div");
element.textContent = "Text"
// or create a textNode and append it
var text = document.createTextNode("Text");
element.appendChild(text);


DOM 업데이트 


요소의 텍스트를 변경하거나 DOM 요소에 새로운 요소를 추가하려는 경우 innerHTML()을 접했을 가능성이 있지만 이를 사용하면 XSS (Cross-Site Scripting) 공격에 노출 될 수 있습니다. 이 문제를 해결하고 HTML을 삭제할 수 있지만 더 안전한 대안이 있습니다.


요소의 텍스트만 읽거나 업데이트하려는 경우 객체의 textContent 속성을 사용하여 현재 텍스트를 반환하거나 업데이트 할 수 있습니다.


// With jQuery
// Update the text of a .button
$(".button").text("New text");
// Read the text of a .button
$(".button").text(); // Returns "New text"

// Without jQuery
// Update the text of a .button
document.querySelector(".button").textContent = "New text";
// Read the text of a .button
document.querySelector(".button").textContent; // Returns "New text"


새 요소를 구성하는 경우 부모 appendChild()의 메서드를 사용하여 해당 요소를 다른 요소에 추가 할 수 있습니다.


// Create div element and append it to .container
$(".container").append($("<div/>"));

// Create a div and append it to .container
var element = document.createElement("div");
document.querySelector(".container").appendChild(element);


다음은 div를 만들고 텍스트와 클래스를 업데이트 한 다음 DOM에 추가하는 방법입니다.


// Create a div
var element = document.createElement("div");

// Update its class
element.classList.add("box");

// Set its text
element.textContent = "Text inside box";

// Append the element to .container
document.querySelector(".container").appendChild(element);


요약하면 


여기에 사용 된 기본 JavaScript 메소드에 대한 포괄적 인 안내서는 아니지만 jQuery에서 벗어나려는 경우 이 안내서가 도움이 되었기를 바랍니다. 다음은 우리가 다루는 방법입니다.