要素の属性を取得又は設定する。
要素の属性を取得する。
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})
<p id="id2">The quick brown fox jumps over the lazy dog.</p>
<script>
$('#id2').attr('class', 'example')
</script>
<p id="id3">The quick brown fox jumps over the lazy dog.</p>
<script>
$('#id3').attr({
dir: 'ltr',
lang: 'en'
})
</script>
<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>