jQuery 属性の追加

Sheeraz Gul 2022年6月21日
jQuery 属性の追加

jQuery attr() メソッドは、HTML 要素に属性を追加するために使用されます。このチュートリアルでは、jQuery で attr() メソッドを使用する方法を示します。

jQuery 属性の追加

jQuery の attr() メソッドを使用して、HTML 要素に属性を追加できます。このメソッドの構文を以下に示します。

$(selector).attr("property", "Value")

ここで

  1. selector は、ID、クラス、または要素の名前にすることができます。
  2. property は属性の名前です。
  3. Value は属性の値です。

例を試してみましょう:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery Add Attribute</title>
      <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
      <script>
         $(document).ready(function(){
             $("#attr").click(function(){
                 $('input[type="checkbox"]').attr("checked", "checked");
             });
         });
      </script>
   </head>
   <body>
      <button type="button" id="attr">Click to Select the Checkbox</button>
      <input type="checkbox">
   </body>
</html>

上記のコードは、チェックされていないチェックボックスをオンにします。このコードは、attr() メソッドで要素名セレクターを使用します。このメソッドでは、プロパティがチェックされ、値もチェックされます。

出力を参照してください:

属性を追加

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

関連記事 - jQuery Attribute