
# Attribute(属性)とは…
属性は要素を拡張し、動作を変更したりメタデータを提供したりします。
属性は常に name="value" の形式を取ります (属性の識別子に関連付けられた値が続きます)。
(MDNより抜粋)
# 今回使うHTMLファイル
今回のゴール:<li>タグにclass属性を追加します
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM</title>
</head>
<body>
<ul>
<li class="first" id="special">私はfirstクラスを持っています。</li>
<a href="first.html" id="link">リンク</a>
<li>私は属性をもっていません。</li> <!-- ←ここにclass属性を追加します -->
</ul>
<!-- JavaScript -->
<script src="main.js"></script>
</body>
</html>
#1,まず、<ul>タグ直下<li>タグのid属性値を取得してみます! 【getAttribute();メソッド】
>```javascript:app.js
// <ul>タグ直下の<li>タグを取得する
const first = document.querySelector('.first');
// id属性値を取得
const idValue = first.getAttribute('id');
// コンソール表示
console.log(idValue); // spesialが表示
#2,次に<a>タグのhref属性値を取得してみます! 【getAttribute();メソッド】
app.js
// <a>タグを取得する
const link = document.getElementById('link');
// href属性値を取得
const showLink = link.getAttribute('href');
// コンソール表示
console.log(showLink); // first.htmlが表示
#3,最後に、属性のない<li>タグにclass属性を追加します 【setAttribute();メソッド】
>```javascript:app.js
// <li>タグを取得する
const last = link.nextElementSibling;
// class="first"を追加
last.setAttribute('class', 'first');
// コンテンツを追加
last.textContent= '私はfirstクラスを持っています。';
// コンソール表示
console.log(last);
#4,デベロッパーツールで確認
<li>タグに属性が追加されていることがわかると思います。