jQuery $(this)のサンプル

jQueryの$(this)のサンプルです。

目次

説明 $(this)とは
サンプル JavaScriptのthisとjQueryの$(this)の比較
  $(this)の親要素を取得する
  $(this)の子要素を取得する

$(this)とは

  • JavaScriptのthisにあたり要素をさします。
  • 対象に対して、jQueryのメソッドを使用できます。

JavaScriptのthisとjQueryの$(this)の比較

JavaScriptのthisとjQueryの$(this)の比較です。

それぞれ、htmlのボタンをconsole.logで確認し、value値を取得してみます。

<input type="button" id="button1" value="ボタン1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
	$("#button1").click(function(){

    // JavaScriptとthis
    console.log(this); // <input type="button" id="button1" value="ボタン1">
    console.log(document.getElementById(this.id).value); // ボタン1

    // jQueryと$(this)
    console.log($(this)); // k.fn.init [input#button1]
    console.log($(this).val()); // ボタン1

	});
});
</script>

1行目は、ボタンです。
8行目は、thisです。この場合、1行目の要素を指します。
以下のように表示されます。



9行目は、this.idとJavaScriptのgetElementByIdメソッドを使用してvalue値を取得しています。

12行目は、$(this)です。これはjQueryオブジェクトになるので、k.fn.initというような名前になっています。以下のように表示されます。


13行目は、1行目のjQueryのvalメソッドでvalue値を取得しています。
→$(this)は、jQueryオブジェクトとなるのでjQueryのメソッドが使用できます。

$(this)の親要素を取得する

親要素を取得する場合は、jQueryのparent()を使用できます。

<style>
  table td {border: 1px solid #000;width: 100px;height: 100px;}
</style>
<table>
  <tr>
    <td>
      <input type="button" id="button1" value="ボタン1" />
    </td>
  </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(function () {
    $("#button1").click(function () {

      $(this).parent().css("border", "1px solid red"); // 枠線が赤になる

    });
  });
</script>

7行目は、ボタンです。
16行目は、$(this)で7行目を指し、parent()で6行目のtdを指します。
そのtdタグに対して枠線の色を赤にしています。

$(this)の子要素を取得する

子要素を取得する場合は、jQueryのchildren()を使用できます。

<style>
  table td {border: 1px solid #000;width: 150px;height: 50px;}
</style>
<table>
  <tr>
    <td>
      <p id="p1">テスト<span>こんにちは</span></p>
    </td>
  </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(function () {
    $("#p1").click(function () {

      $(this).children().css("color", "red"); // 文字が赤になる

    });
  });
</script>

7行目は、文字列です。
16行目は、$(this)で7行目のpタグを指し、children()でspanタグを指します。
そのspanタグの文字に対して色を赤にしています。

関連の記事

jQuery テーブルのクリックしたセルの値を取得(next)

△上に戻る