1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

prop(attr)の使い方と属性値の取得・設定

Posted at

prop()とは?

「prop()」はHTML要素に付与されている「id・class・name」…などの属性や、「checked・selected」…などのプロパティを取得できる。特によく使われるのが、フォームをjQueryで操作する時に必須となる「checked」などのプロパティを扱うケース。

HTML要素の属性を取得する方法

<body>
<p id="text">サンプルテキスト</p>

<script>
    var id = $('p').prop('id');

    console.log( id );//text
</script>
</body>

HTML要素の属性を設定する方法

<body>
<p id="text">サンプルテキスト</p>

<script>
    var id = $('p').prop('id', 'sample');

    console.log( id );//sample
</script>
</body>

prop()の引数にfunctionを設定する

<form id="myForm">
  <input type="text" name="name">
  <button type="submit" id="submitBtn">送信</button>
</form>

<script>
$('#myForm').on('submit', function() {
  $('#submitBtn').prop('disabled', function(i, old) {
    return !old; // 現在の状態を反転 → disabledになる
  });
});
</script>

複数の属性を設定する方法

<input type="checkbox" id="chk1">

<script>
$('#chk1').prop({
  checked: true,
  disabled: false
});
</script>

prop()とattr()を区別するには?

attr()で「checked」を取得する

<body>
<input type="checkbox" checked>

<script>
    var check = $('input').attr('checked');

    console.log( check );//checked
</script>
</body>

「checked」が存在していれば実行結果のように「checked」の文字列が取得でき、無ければ「undefined」が取得できる

prop()で「checked」を取得する

<body>
<input type="checkbox" checked>

<script>
    var check = $('input').prop('checked');

    console.log( check );//true
</script>
</body>

attr()は、checkedの記述があるかどうかを確認する
prop()は、checkedの状態(チェックされたかどうか)を確認する

まとめ

prop()は属性を取得したり再設定することができる
prop()は引数に関数を使って条件分岐することも可能
attr()は属性の存在有無だけを確認するが、prop()は状態を確認する

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?