jQuery prop()メソッド

❮jQueryHTML/ CSSメソッド

「color」という名前のプロパティを追加および削除します。

$("button").click(function(){
  var $x = $("div");
  $x.prop("color", "FF0000");
  $x.append("The color property: " + $x.prop("color"));
  $x.removeProp("color");
});

定義と使用法

prop()メソッドは、選択した要素のプロパティと値を設定または返します。

このメソッドを使用してプロパティ値を返す場合、最初に一致した要素の値を返します

このメソッドを使用してプロパティ値を設定すると、一致した要素のセットに対して1つ以上のプロパティ/値のペアが設定されます。

注: prop()メソッドは、DOMプロパティ(tagName、nodeName、defaultCheckedなど)や独自のカスタムメイドのプロパティなどのプロパティ値を取得するために使用する必要があります。

ヒント: HTML属性を取得するには、代わりにattr()メソッドを使用します。

ヒント:プロパティを削除するには、removeProp()メソッドを使用します。


構文

プロパティの値を返します。

$(selector).prop(property)

プロパティと値を設定します。

$(selector).prop(property,value)

関数を使用してプロパティと値を設定します。

$(selector).prop(property,function(index,currentvalue))

複数のプロパティと値を設定します。

$(selector).prop({property:value, property:value,...})

Parameter Description
property Specifies the name of the property
value Specifies the value of the property
function(index,currentvalue) Specifies a function that returns the property value to set
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current property value of selected elements

自分で試してみてください-例


prop()とattr()は異なる値を返す場合があります。この例は、チェックボックスの「チェック済み」ステータスを返すために使用した場合の違いを示しています。


❮jQueryHTML/ CSSメソッド