はじめに
最近、レガシーなプロジェクトで jQuery を触る機会があって、いろいろとわからないことがあったため、個人的なチートシートをまとめることにしました。
バージョン: jQuery 3.x 系を前提にしています
基本構文
// DOM 読み込み完了後に実行
$(document).ready(function () {
// 処理
});
// 省略形(よく使う)
$(function () {
// 処理
});
// 基本のセレクタ書き方
$(selector).method();
セレクタ一覧
| セレクタ | 説明 |
|---|---|
$("*") |
全要素 |
$(".class") |
クラス名 |
$("#id") |
ID |
$("div") |
タグ名 |
$("div, p") |
複数指定 |
$("parent > child") |
直下の子要素 |
$("ancestor descendant") |
子孫要素 |
$(":hidden") |
非表示要素 |
$(":visible") |
表示中の要素 |
$(":contains('text')") |
指定テキストを含む要素 |
$(":first") |
最初の要素 |
$(":last") |
最後の要素 |
$(":even") |
偶数インデックス(0始まり) |
$(":odd") |
奇数インデックス |
$(":eq(n)") |
n番目の要素 |
DOM 操作
要素の取得・変更
// テキスト
$("#el").text(); // 取得
$("#el").text("hello"); // 変更
// HTML
$("#el").html(); // 取得
$("#el").html("<b>Hi</b>"); // 変更
// フォームの値
$("input").val(); // 取得
$("input").val("value"); // 変更
// 属性
$("#el").attr("href"); // 取得
$("#el").attr("href", "/top"); // 変更
$("#el").removeAttr("href"); // 削除
要素の追加・削除
// 子要素として末尾に追加
$("#parent").append("<p>追加</p>");
$("<p>追加</p>").appendTo("#parent");
// 子要素として先頭に追加
$("#parent").prepend("<p>先頭</p>");
// 兄弟要素として後ろに追加
$("#el").after("<p>後ろ</p>");
// 兄弟要素として前に追加
$("#el").before("<p>前</p>");
// 要素の削除
$("#el").remove(); // イベントも一緒に削除
$("#el").detach(); // イベントを保持したまま削除(再挿入前提)
// 子要素をすべて削除
$("#el").empty();
// 要素の置換
$("#el").replaceWith("<div>新しい要素</div>");
// ラップ
$("#el").wrap("<div class='wrapper'></div>");
$(".items").wrapAll("<div class='container'></div>");
// ラップ解除
$("#el").unwrap();
// 要素のコピー
$("#el").clone();
$("#el").clone(true); // イベントも含めてコピー
CSS 操作
// 1プロパティ
$("#el").css("color"); // 取得
$("#el").css("color", "red"); // 変更
// 複数プロパティ
$("#el").css({
color: "red",
fontSize: "16px",
backgroundColor: "#fff",
});
// クラス操作
$("#el").addClass("active");
$("#el").removeClass("active");
$("#el").toggleClass("active");
$("#el").hasClass("active"); // boolean
// サイズ
$("#el").width(); // コンテンツ幅
$("#el").height(); // コンテンツ高さ
$("#el").innerWidth(); // padding含む
$("#el").innerHeight();
$("#el").outerWidth(); // border含む
$("#el").outerHeight();
$("#el").outerWidth(true); // margin含む
$("#el").outerHeight(true);
// 位置
$("#el").offset(); // { top, left } ドキュメント基準
$("#el").position(); // { top, left } 親要素基準
$(window).scrollTop(); // スクロール位置(縦)
$(window).scrollLeft(); // スクロール位置(横)
表示・非表示(エフェクト)
// 基本
$("#el").hide(); // display: none
$("#el").show(); // 表示
$("#el").toggle(); // 切り替え
// スピード指定("slow" / "fast" / ミリ秒)
$("#el").hide("slow");
$("#el").show(300);
$("#el").toggle("fast", function() {
console.log("完了"); // コールバック
});
// フェード
$("#el").fadeIn();
$("#el").fadeOut(300);
$("#el").fadeToggle("slow");
$("#el").fadeTo("slow", 0.5); // 指定した透明度まで
// スライド
$("#el").slideDown();
$("#el").slideUp(300);
$("#el").slideToggle("fast");
// カスタムアニメーション
$("#el").animate(
{
opacity: 0.5,
marginTop: "20px",
width: "200px",
},
500, // duration (ms)
"swing", // easing("swing" or "linear")
function () { // callback
console.log("アニメーション完了");
}
);
// アニメーション制御
$("#el").stop(); // 現在のアニメーションを停止
$("#el").stop(true); // キューも削除
$("#el").stop(true, true); // キュー削除 & 最終状態にジャンプ
$("#el").finish(); // すべてのアニメーションを完了状態にする
$("#el").delay(500); // 次のアニメーションまで遅延
イベント
// クリック
$("#el").click(function () { ... });
$("#el").on("click", function () { ... });
// ダブルクリック
$("#el").dblclick(function () { ... });
// マウス
$("#el").mouseenter(function () { ... });
$("#el").mouseleave(function () { ... });
$("#el").hover(
function () { /* enter */ },
function () { /* leave */ }
);
// キーボード
$(document).keydown(function (e) { console.log(e.key); });
$(document).keyup(function (e) { ... });
$(document).keypress(function (e) { ... }); // 非推奨
// フォーム
$("input").focus(function () { ... });
$("input").blur(function () { ... });
$("input").change(function () { ... });
$("input").input(function () { ... });
$("form").submit(function (e) {
e.preventDefault(); // デフォルト動作を止める
...
});
// ウィンドウ
$(window).resize(function () { ... });
$(window).scroll(function () { ... });
// イベントの削除
$("#el").off("click");
$("#el").off("click", handler);
// 一度だけ実行
$("#el").one("click", function () { ... });
// イベントの委譲(動的に追加された要素にも効く)
$(document).on("click", ".dynamic-el", function () { ... });
// or
$("#static-parent").on("click", ".dynamic-el", function () { ... });
// イベントを手動で発火
$("#el").trigger("click");
トラバース(DOM 探索)
// 親・祖先
$("#el").parent(); // 直親
$("#el").parents(); // 全祖先
$("#el").parents("div"); // 条件フィルタ
$("#el").parentsUntil(".stop"); // .stop まで遡る
$("#el").closest(".wrapper"); // 自身も含めて一番近い祖先
// 子・子孫
$("#el").children(); // 直下の子要素
$("#el").children(".active"); // フィルタ
$("#el").find("p"); // 子孫すべてから検索
$("#el").contents(); // テキストノードも含む
// 兄弟
$("#el").siblings();
$("#el").siblings(".active");
$("#el").next(); // 直後の兄弟
$("#el").nextAll(); // 後ろの全兄弟
$("#el").nextUntil(".stop");
$("#el").prev(); // 直前の兄弟
$("#el").prevAll();
$("#el").prevUntil(".stop");
// フィルタリング
$("li").first();
$("li").last();
$("li").eq(2); // インデックス指定
$("li").filter(".active");
$("li").not(".active");
$("li").has("span"); // spanを持つliに絞る
$("li").is(".active"); // boolean
// チェーンのリセット
$("ul").find("li").addClass("item").end().addClass("list");
// end() で $("ul") に戻る
Ajax
// $.ajax(フル設定)
$.ajax({
url: "/api/data",
type: "GET", // "POST" / "PUT" / "DELETE"
data: { id: 1 },
dataType: "json",
success: function (res) {
console.log(res);
},
error: function (jqXHR, status, err) {
console.error(err);
},
complete: function () {
console.log("完了");
},
});
// Promise スタイル(こっちが今っぽい)
$.ajax({ url: "/api/data", type: "GET" })
.done(function (res) { console.log(res); })
.fail(function (err) { console.error(err); })
.always(function () { console.log("常に実行"); });
// 短縮形
$.get("/api/data", function (res) { ... });
$.post("/api/data", { name: "test" }, function (res) { ... });
$.getJSON("/api/data", function (res) { ... });
// フォームのシリアライズ
$("form").serialize(); // クエリストリング形式
$("form").serializeArray(); // オブジェクト配列形式
ユーティリティ
// each(ループ)
$("li").each(function (index, element) {
console.log(index, $(element).text());
});
// map(新しいjQueryオブジェクトを返す)
const texts = $("li").map(function (i, el) {
return $(el).text();
}).get(); // 配列に変換
// フィルタ(ネイティブのfilterと同じイメージ)
$("li").filter(function (i) {
return $(this).text().includes("jQuery");
});
// データの保存
$("#el").data("key", "value"); // 保存
$("#el").data("key"); // 取得
$("#el").removeData("key"); // 削除
// 型チェック
$.isArray([]); // true
$.isFunction(fn); // true
$.isNumeric("3"); // true
$.type({}); // "object"
// 拡張
$.extend({ method: function() {} }); // jQueryに追加
$.fn.extend({ method: function() {} }); // プラグイン的に追加
// trim
$.trim(" hello "); // "hello"(ES6以降はString.prototype.trimでOK)
まとめ
jQuery はレガシーとか言われつつも、まだ使用している案件はいくつかある。今後もメソッドに迷わないようにまとめたので、同じく「あれどうだっけ」ってなる人の参考になればと思います。