1. 선택자

// 기본
$(".box");

document.querySelector(".box"); // 첫번째만 반환함 
document.querySelectorAll(".box"); // 모두 반환함 nodeList 형태라고 하는데 배열이라고 생각하면 편함


// find
var container = $(".container");
container.find(".box");

var container = document.querySelector(".container");
container.querySelector(".box");

2. 기능실행

$(".box").hide();

// 한개
document.querySelector(".box").style.display = "none";
// 여러개
document.querySelectorAll(".box").forEach(box => { box.style.display = "none" })

3. 탐색

$(".box").next();
$(".box").prev();
$(".box").parent();

var box = document.querySelector(".box");
box.nextElementSibling;
box.previousElementSibling;
box.parentElement;

4. 요소

// 요소 추가
$("<div/>");
$("<span/>");

document.createElement("div");
document.createElement("span");


// 요소에 텍스트 추가
var element = document.createElement("div");
element.textContent = "Text"

var text = document.createTextNode("div");
element.appendChild(text);


// 요소의 속성 수정 
$(".button").text("New text");

document.querySelector(".button").textContent = "New text";

// 요소의 속성값 가져오기
$(".button").text();

document.querySelector(".button").textContent;


// 요소에 하위 요소 추가
$(".container").append($("<div/>"));

var element = document.createElement("div");
document.querySelector(".container").appendChild(element);

4. 이벤트 추가

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

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


// 동적으로 추가하는 요소에도 이벤트 추가
$(".search-container").on("click", ".search-result", handleClick); // 기존 요소와 추가될 요소까지

var searchElement = document.createElement("div");
document.querySelector(".search-container").appendChild(searchElement);
searchElement.addEventListener("click", handleClick); // 추가한 요소에 이벤트 추가하기


// Trigger
$(document).trigger("myEvent");
$(".box").trigger("myEvent");

document.dispatchEvent(new Event("myEvent"));
document.querySelector(".box").dispatchEvent(new Event("myEvent"));

5. Style (CSS)

// 하나라면
$(".box").css("color", "#000");

document.querySelector(".box").style.color = "#000";


// 여러개라면
$(".box").css({
  "color": "#000",
  "background-color": "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";


// Class명 추가/삭제/토글
$(".box").addClass("focus");
$(".box").removeClass("focus");
$(".box").toggleClass("focus");

// 한개
var box = document.querySelector(".box");
box.classList.add("focus");
box.classList.remove("focus");
box.classList.toggle("focus");

// 여러개
var box = document.querySelector(".box");
box.classList.add("focus", "highlighted");
box.classList.remove("focus", "highlighted");

// 상호 베타적인 토글용 2개의 Class를 번갈아가며 써야 한다면
document.querySelector(".box").classList.replace("focus", "blurred");


// Class명을 가지고 있는지 확인
$(".box").hasClass("focus");

document.querySelector(".box").classList.contains("focus");

6. Document Ready

$(document).ready(function() { 
	// 소스
});

var ready = (callback) => {
  if (document.readyState != "loading") callback();
  else document.addEventListener("DOMContentLoaded", callback);
}

ready(() => { 
	// 소스
});

7. Ajax

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


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

 

출처를 기반으로 다시 정리함

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

 

Cheat sheet for moving from jQuery to vanilla JavaScript

This reference guide will help you convert jQuery's most common patterns to vanilla JavaScript

tobiasahlin.com

 

'Javascript' 카테고리의 다른 글

fetch로 file download (feat. express)  (0) 2023.05.15
정렬 sort  (0) 2021.04.01
키보드를 이용한 Input text 포커스 이동  (0) 2021.03.15
String to Date / Date to String  (0) 2020.12.17
숫자에 콤마와 언콤마를 편하게  (0) 2016.06.27

// 숫자 타입에서 쓸 수 있도록 format() 함수 추가

Number.prototype.format = function(){

    if(this==0) return 0;

 

    var reg = /(^[+-]?\d+)(\d{3})/;

    var n = (this + '');

 

    while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2');

 

    return n;

};

 

// 문자열 타입에서 쓸 수 있도록 format() 함수 추가

String.prototype.format = function(){

    var num = parseFloat(this);

    if( isNaN(num) ) return "0";

 

    return num.format();

};


// 콤마가 들어간 문자열을 콤마 제거하면서 숫자형 반환

String.prototype.unformat = function(){

var str = this.replace(/,/g,'');

var num = parseFloat(str);

if( isNaN(num) ) {

return "0";

}


return String(num);

};

 

 

// 숫자 타입 test

var num = 123456.012;

console.log(num.format());               // 123,456.012

 

num = 13546745;

console.log(num.format());               // 13,546,745

 

// 문자열 타입 test

console.log("12348".format());           // 12,348

console.log("12348.6456".format());      // 12,348.6456


출처: http://stove99.tistory.com/113


배열의 특정 요소 제거


배열 = 배열.splice($.inArray("특정요소", 배열),1);



배열을 문자열로 출력


배열 = 배열.join("합칠 문자열");


var nm = "listVo[0].col1";

// 괄호안의 문자 추출하기
nm = nm.match(/\[.*\]/gi);
nm += "";
nm = nm.split("[").join("");
nm = nm.split("]").join("");

// 괄호문자 치환하기
nm = nm.replace(/\[.*\]/gi, '[1]');

'Javascript' 카테고리의 다른 글

String to Date / Date to String  (0) 2020.12.17
숫자에 콤마와 언콤마를 편하게  (0) 2016.06.27
숫자에 천단위 콤마 찍기  (0) 2014.10.01
형변환, 숫자체크  (0) 2014.06.26
Date Format  (0) 2014.04.04

문자 -> 숫자

Number(text);
parseFloat(number);


숫자 -> 문자

String(number);


진법

parseInt(number, radix);


숫자체크

function isNumberic(text) {
    return typeof Number(text) === 'number' && isFinite(text);
}


'Javascript' 카테고리의 다른 글

정규식으로 괄호 안의 문자 추출과 치환하기  (0) 2015.07.09
숫자에 천단위 콤마 찍기  (0) 2014.10.01
Date Format  (0) 2014.04.04
replaceAll 구현  (0) 2013.09.05
팝업을 정중앙으로 띄울때  (0) 2012.04.27

자바스크립트에는 replace는 있지만 replaceAll은 없다. 그래서 replace를 사용할 경우 치환은 최초 1회만 해준다.

가장 편하고 간단한 방법은 split으로 쪼개고 join으로 합치는 방법이다.

이걸 아래처럼 래핑쓰면 편리하다.


function replaceAll(text, before, after) {

    return text.split(before).join(After);

}


'Javascript' 카테고리의 다른 글

정규식으로 괄호 안의 문자 추출과 치환하기  (0) 2015.07.09
숫자에 천단위 콤마 찍기  (0) 2014.10.01
형변환, 숫자체크  (0) 2014.06.26
Date Format  (0) 2014.04.04
팝업을 정중앙으로 띄울때  (0) 2012.04.27

+ Recent posts