셀렉터
기본 셀렉터
$("p") // all

elements $(".btn") // class selector $("#main") // ID selector $("ul > li") // direct children $("input[type='text']") // attribute selector

주요 셀렉터
$('*')모든 요소
$('a, span')여러 셀렉터
$(':first')첫 번째로 매칭된 요소
$(':last')마지막으로 매칭된 요소
$(':even') / $(':odd')짝수/홀수 인덱스 요소
$(':visible') / $(':hidden')가시성 필터
$(':contains(text)')텍스트를 포함하는 요소
$(':has(selector)')셀렉터와 매칭되는 하위 요소를 가진 요소
DOM 조작
콘텐츠 및 구조
$("#el").html("Bold"); // set inner HTML $("#el").text("Plain text"); // set text content $("ul").append("
  • New
  • "); // add at end $("ul").prepend("
  • First
  • "); // add at start
    삽입 및 제거
    $("

    Hello

    ").insertAfter("#el"); // insert after $("

    Hi

    ").insertBefore("#el"); // insert before $("#el").remove(); // remove element from DOM $("#el").empty(); // remove all children
    메서드
    .html()내부 HTML 가져오기/설정
    .text()텍스트 콘텐츠 가져오기/설정
    .append() / .prepend()끝/처음에 자식 추가
    .after() / .before()뒤/앞에 형제 요소 삽입
    .wrap()새 부모로 요소 감싸기
    .clone()요소 깊은 복사
    .replaceWith()요소 교체
    이벤트
    이벤트 바인딩
    $(".btn").on("click", function () { $(this).toggleClass("active"); }); $(document).on("click", ".dynamic", handler); // delegation $(".btn").off("click"); // remove handler
    단축 메서드
    .click(fn)클릭 핸들러
    .hover(fnIn, fnOut)마우스 진입/이탈
    .focus() / .blur()포커스 획득/해제
    .change(fn)값 변경 (input/select)
    .submit(fn)폼 제출
    .keydown() / .keyup()키보드 이벤트
    문서 준비
    $(document).ready(function () { /* DOM loaded */ }); $(function () { /* shorthand */ });
    효과 및 애니메이션
    보이기 / 숨기기 / 토글
    $("#el").hide(400); // hide with animation $("#el").show(400); // show with animation $("#el").toggle(); // toggle visibility $("#el").fadeIn(600); // fade in $("#el").slideDown(400); // slide down
    커스텀 애니메이션
    $("#el").animate({ opacity: 0.5, left: "+=50px", height: "toggle" }, 1000, function () { /* complete */ });
    효과 메서드
    .fadeIn() / .fadeOut()투명도 애니메이션
    .fadeToggle()페이드로 토글
    .slideDown() / .slideUp()높이 애니메이션
    .animate(props, ms)커스텀 CSS 애니메이션
    .stop()현재 애니메이션 중지
    .delay(ms)다음 대기 효과 지연
    AJAX
    단축 메서드
    $.get("/api/data", function (data) { console.log(data); }); $.post("/api/data", { name: "Alice" }, function (res) {}); $.getJSON("/api/items", function (json) {}); $("#el").load("/fragment.html"); // load HTML into element
    $.ajax 전체 사용
    $.ajax({ url: "/api/data", method: "POST", data: JSON.stringify({ key: "val" }), contentType: "application/json", success: (res) => console.log(res), error: (xhr) => console.error(xhr.status) });
    AJAX 옵션
    url요청 URL
    methodHTTP 메서드 (GET, POST, ...)
    data전송할 데이터
    dataType기대하는 응답 타입
    contentType요청 콘텐츠 타입
    success / error콜백 함수
    headers커스텀 요청 헤더
    탐색
    트리 탐색
    $("li").parent(); // direct parent $("li").parents("ul"); // all matching ancestors $("ul").children("li"); // direct children $("ul").find(".active"); // all matching descendants $("li").siblings(); // sibling elements
    탐색 메서드
    .parent() / .parents()직접 부모 / 모든 상위 요소
    .children() / .find()직접 자식 / 모든 하위 요소
    .siblings()모든 형제 요소
    .next() / .prev()다음/이전 형제
    .closest(sel)셀렉터와 매칭되는 가장 가까운 상위 요소
    .first() / .last()매칭된 집합의 첫 번째/마지막
    .eq(index)인덱스의 요소
    .filter(sel)매칭되는 요소로 축소
    속성 및 CSS
    속성
    $("img").attr("src"); // get attribute $("img").attr("src", "new.jpg"); // set attribute $("img").removeAttr("title"); // remove attribute $("input").prop("checked", true); // set property
    CSS 및 클래스
    $(".box").css("color", "red"); // set single style $(".box").css({ color: "red", fontSize: "14px" }); // multi $("p").addClass("highlight"); $("p").removeClass("highlight"); $("p").toggleClass("active"); $("p").hasClass("active"); // returns boolean
    값 및 직렬화
    $("input").val(); // get value $("input").val("new value"); // set value $("form").serialize(); // "name=Alice&age=30" $("form").serializeArray(); // [{name, value}, ...]
    폼 셀렉터
    $(":input")모든 폼 요소
    $(":checked")체크된 체크박스/라디오
    $(":selected")선택된 option 요소
    $(":disabled")비활성화된 요소
    $(":text")텍스트 입력
    유틸리티
    배열 및 객체 헬퍼
    $.each([1, 2, 3], function (i, val) { /* iterate */ }); $.each(obj, function (key, val) { /* iterate object */ }); $.extend({}, defaults, options); // merge objects $.inArray("b", ["a", "b", "c"]); // returns 1 (index)
    유틸리티 메서드
    $.each(arr, fn)배열 또는 객체 순회
    $.extend(target, ...)객체 병합 (얕은 복사)
    $.inArray(val, arr)값의 인덱스 (-1이면 없음)
    $.isArray(obj)배열인지 확인
    $.trim(str)앞뒤 공백 제거
    $.parseJSON(str)JSON 문자열 파싱
    $.map(arr, fn)배열 요소 변환
    주요 패턴
    체이닝
    $("ul") .find("li") .addClass("item") .first() .css("font-weight", "bold");
    플러그인 패턴
    $.fn.highlight = function (color) { return this.each(function () { $(this).css("background", color || "yellow"); }); }; $("p").highlight("pink");
    충돌 해결
    // Avoid $ conflicts with other libraries jQuery.noConflict(); jQuery(document).ready(function ($) { $(".btn").click(handler); // $ safe inside });