LoginSignup
15
12

More than 5 years have passed since last update.

jQueryの意外に知られていない仕様 セレクタの絞込方法(第二引数にcontext ありの場合)

Last updated at Posted at 2017-05-30

第三者のコード解析中にあまり見かけない記述方法がありましたので、書き留めておきます。
以下のようなコードです。(実際はもっと複雑な記述でしたが、問題箇所に言及します)

$( ".hit", "#btnA" ).addClass( "active" );

「$( ".hit", "#btnA" )」の記述が?????となりました。

ちなみにHTMLは以下の構造です。

<div id="#btnA">
<div class="hit">ボタン</div>
</div>

「$( ".hit, #btnA" )」の記述なら
セレクター".hit"と"#btnA"に"active"クラスをつけるということがわかりますが、
それとは違います。

いろいろと調べた結果、公式ドキュメントに記述がありました。
http://api.jquery.com/jQuery/#jQuery-selector-context

jQuery( selector [, context ] )

Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:
When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

第二引数にコンテキストを入力した場合、その指定で限定されるのです。
要するに、findを使った以下と同じ指定になるのです。

$( "#btnA" ).find(".hit").addClass( "active" );

これで納得!詳しくは公式ドキュメントをご確認ください。

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12