復習がてら…( ˘ω˘)スヤァ
気が向いたら図を追加します。気が向いたら…
基本的なセレクタの使い方
// タグ名(input,formなど)
$("div")
// クラス名
$(".Class")
// ID
$("#Id")
// 全要素の取得(まず使うことはない)
$("*")
サンプルソース
各種セレクタの結果を確認するために以下のサンプルソースを用意しました。
「親(oya)」→「子(ko)」→「孫(mago)」の順に階層を作っています。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- ID -->
<div id="oya">
<!-- 「oya」IDの階層にあるinputタグ -->
<input type="text" name="id_oya_textbox">
<div id="ko">
<!-- 「ko」IDの階層にあるinputタグ -->
<input type="text" name="id_ko_textbox">
<div id="mago">
<!-- 「mago」IDの階層にあるinputタグ -->
<input type="text" name="id_mago_textbox">
</div>
</div>
<!-- 「kakushigo」IDの階層にあるinputタグ -->
<div id="kakushigo">
<input type="text" name="id_kakushigo_textbox">
</div>
</div>
<!-- クラス -->
<div class="oya">
<!-- 「oya」クラスの階層にあるinputタグ -->
<input type="text" name="class_oya_textbox">
<div class="ko">
<!-- 「ko」クラスの階層にあるinputタグ -->
<input type="text" name="class_ko_textbox">
<div class="mago taro">
<!-- 「mago」「taro」クラスの階層にあるinputタグ -->
<input type="text" name="class_mago_taro_textbox">
</div>
<div class="mago jiro">
<!-- 「mago」「jiro」クラスの階層にあるinputタグ -->
<input type="text" name="class_mago_jiro_textbox">
</div>
</div>
</div>
AND,OR条件指定
AND指定の場合はタグ名、クラス名、IDを連結して書き、
OR指定の場合は「,」で区切って書く。
AND指定
// ①divタグで「oya」クラスを持っている要素を取得
$("div.oya")
// ②divタグで「mago」クラスと「taro」クラスを持っている要素を取得
$("div.mago.taro")
①実行結果
②実行結果
OR指定
// ③「taro」クラスまたは「jiro」クラスを持っている要素を取得
$(".taro, .jiro")
// 組み合わせも可能
$("div.taro, div.jiro")
③実行結果
親子関係
// ④親クラスのinputタグを取得(子クラス以下の階層は取得対象外)
$("div.oya > input")
// ⑤子から親を参照する方法
// 「ko」クラスから見て一階層上にあるdivタグを取得
$("div.ko").parent("div")
④実行結果
⑤実行結果
先祖-子孫関係
// ⑥親クラス内の全てのinputタグを取得
$("div.oya input")
// ⑦「mago」クラスから見て上の階層にある全てのdivタグを取得する
$(".mago").parents("div")
⑥実行結果
⑦実行結果
属性
// inputタグでname属性を持つ要素
$("input[name]")
// 完全一致
$("input[name=id_ko_textbox]")
// 先頭一致
$("input[name^=id]")
// 部分一致
$("input[name*=ko]")
// 末尾一致
$("input[name$=textbox]")
// inputタグでtype属性が「text」の要素
$("input[type='text']")
続きは後日…















