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

More than 3 years have passed since last update.

JavaScript DOM操作で要素の追加と削除を行う

Last updated at Posted at 2020-12-27

#要素を追加する

index.html
    <!DOCTYPE html>
    <html lang="ja">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <h1>JavaScript Practice</h1>
        <dl id="credit">
            <dt>今日の天気</dt>
            <dd class="weather">晴れ</dd>
        </dl>
        <script src="index.js"></script>
    </body>

    </html>

#1,どこに要素を追加するのかツリー構造の確認(変更前)

#2,appendChild()メソッドを使う

document.appendChild();メソッドを使用する

index.js

// タグを生成
let element = document.createElement("p");
// テキストを生成
let text = document.createTextNode("いいお天気ですね");
// bodyタグに要素を追加
document.querySelector("body").appendChild(element).appendChild(text);


#3,どこに要素が追加されたかツリー構造の確認(変更後)
><img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/ac1c6899-21e9-f32f-2f2f-53fb9e562a14.png" width="600">

#4,要素の削除を行う
>**removeChild();**メソッドを使用する

>```javascript:index.js
// 要素を削除
    let element2 = document.getElementById("credit");
    let parent = element2.parentElement;
    parent.removeChild(element2);

#5,要素の確認

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