jQueryオブジェクト .attr()

要素の属性を取得又は設定する。

属性の取得

要素の属性を取得する。

jQueryObject.attr(attribute)

要素の属性を取得する例を次に示す。

<p id="p1" lang="en">
  In a hole in the ground there lived a hobbit.
</p>
<script>
  let lang = $('#p1').attr('lang')
  console.log(lang)
</script>

In a hole in the ground there lived a hobbit.

属性の設定

要素の属性を設定する。

jQueryObject.attr(attribute, value)
jQueryObject.attr(map)
jQueryObject.attr(attribute, function(index, old-value){statements})
attribute
属性の名前
<p id="id2">The quick brown fox jumps over the lazy dog.</p>
<script>
  $('#id2').attr('class', 'example')
</script>
value
属性に設定する値
map
属性名と属性値のペアを格納したMapオブジェクト
<p id="id3">The quick brown fox jumps over the lazy dog.</p>
<script>
  $('#id3').attr({
    dir: 'ltr',
    lang: 'en'
  })
</script>
function
新しい属性値を戻り値として返す関数
<p id="id4">In a hole in the ground there lived a hobbit.</p>
<script>
  $('#id4').attr('title', function(index, attr){
    return 'The Hobbit by J. R. R. Tolkien'
  })
</script>
index
要素の番号
old-value
変更前の属性値

関連記事