0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript getAttribute();(属性の取得)とsetAttribute();(属性の追加)

Posted at

# 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>タグに属性が追加されていることがわかると思います。

get.png

0
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?