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?

【コア機能】JavaScript2

Posted at

【コア機能】HTML,CSSに引き続き、JavaScriptを実装していきます。
こちらの記事では[4][5][6]までを掲載しております。

【実装内容】
[4]リストを個別で削除できるボタンを実装する。
- 4-1 liを増やした時と同じようにdelete要素を増やす

[5]リストを個別で終了させられる[完了]ボタンを実装する。
- 5-1完了ボタン実装
- 5-2親要素・子要素とDOMツリー
[6][完了]ボタンが押されたら右横にリアルタイムの時間が表示される。
[7]全体のコードを確認
[8]Element/createElementの少し確認・おさらい
[感想]

[4]リストを個別で削除できるボタンを実装する。

4-1 liを増やした時と同じようにdelete要素を増やす

    const newList = document.createElement('li');
    newList.textContent = text;

    const deleteButton = document.createElement('button');
    deleteButton.textContent = '削除';
    deleteButton.addEventListener('click', function() {
        list.removeChild(newList);
    });
    newList.appendChild(deleteButton);
    list.appendChild(newList);

createElemntでliを作成している下に同じように
createElement('button')を記述する。
クリックすれば子要素が削除されるようにイベントハンドラーを設定。

[5]リストを個別で終了させられる[完了]ボタンを実装する。

5-1完了ボタン実装
完了ボタンも同じ要領で作成できそうなので、つくってみました。

       // Create a new list item and append it to the list
    const newList = document.createElement('li');
    newList.textContent = text;
    // Create delete button
    const deleteButton = document.createElement('button');
    deleteButton.textContent = '削除';
    deleteButton.addEventListener('click', function() {
        list.removeChild(newList);
    });
    // create done button
    const doneButton = document.createElement('button');
    doneButton.textContent = '完了';
    doneButton.addEventListener('click', function() {
        newList.style.textDecoration = 'line-through';
    });

    list.appendChild(newList);
    newList.appendChild(deleteButton);
    newList.appendChild(doneButton);
});

できました!
ついでに最後の3行の順番を上からの順番通りに並べ替えました。
視覚的に統一感がないと読みにくいかな?と感じたため、変更したポイントでUIUXには支障はない。。はずです。

5-2親要素・子要素とDOMツリー

---親要素・子要素のポイント---
最後3行のlistnewListの使い分けはVSCが自動で生成してくれたため、自力で意識できていない箇所でした。
ちょっとここで整理しておきます。

    list.appendChild(newList);
    newList.appendChild(deleteButton);
    newList.appendChild(doneButton);

どこに指示を出したいか?がポイントとなりますが、
newListdeleteButtondoneButtonそれぞれどこに指示を出して作成削除完了ができていると思いますか?
指示の出し先は親要素で、全て親要素にお願いしてそれぞれの動作を発動させてもらってます。
その親要素listnewListです。
listnewListの関係はlistnewListの親。
以下、DOMツリーを見ればもう少し意味が分かると思います。

list (親: <ul>)
└─ newList (<li>)
   ├─ deleteButton (<button>削除)
   └─ doneButton   (<button>完了)

いつのまにlistが親になった!?!?!
ここです↓

 list.appendChild(newList);

逆にこのコードが記述されるまでは何でもないただの文字群。
この挿入の記述で親子を決めているようなんです。

実際console.logでも確認できましたので、シェアします。
newListに対してappend前と後で親要素にどのような変化があったか?console.logで見てみました。

    // Create a new list item and append it to the list
    const newList = document.createElement('li');
    newList.textContent = text;
    // Create delete button
    const deleteButton = document.createElement('button');
    deleteButton.textContent = '削除';
    deleteButton.addEventListener('click', function() {
        list.removeChild(newList);
    });
    // create done button
    const doneButton = document.createElement('button');
    doneButton.textContent = '完了';
    doneButton.addEventListener('click', function() {
        newList.style.textDecoration = 'line-through';
    });

    console.log('append前:', newList.parentNode);

    // newList.appendChild(label);
    list.appendChild(newList);
    newList.appendChild(deleteButton);
    newList.appendChild(doneButton);

    console.log('append後:', newList.parentNode);

結果
スクリーンショット 2025-10-17 18.30.54.png
append前はnullだったのに、append後には親要素が表示されました!
なーるほどね。。。すごい。

同じようにnewListも以下のタイミングでdeleteButtondoneButtonの親要素になっています。

    newList.appendChild(deleteButton);
    newList.appendChild(doneButton);

[6][完了]ボタンが押されたら右横にリアルタイムの時間が表示される。

JavaScriptで時間を取得するオブジェクトは

let d = new Date();
引数なしでDateオブジェクトを生成した場合、既定で現在の日時がセットされます。

さらに取得したDateオブジェクトを文字列に変換する方法は

(toLocaleString());
参考:JavaScript本格入門改訂3版 5.4

これを[Add]ボタンを押したら怒るイベントハンドラーの最下部に挿入します。

  const timeStamp = document.createElement('span');
    timeStamp.textContent = ` (${new Date().toLocaleString()})`;
    newList.appendChild(timeStamp);

spanタグを作成したのは、後々CSSで少し触りたいからです。

new Date()で日時を取得し、
.toLocaleString()で文字列に変換、
${}バッククォートで変数を展開し結果を文字列に埋め込む。
newList.appendChild(timeStamp);完了ボタンのイベントハンドラー内に書かないとtimeStamp is not definedでエラーとなりtimestampが表示されなかったため。

[7]全体のコード確認

const buttonAdd = document.getElementById('button-add');
const list = document.getElementById('list');
const selectDestinations = document.getElementById('select-destinations');
const selectPackages = document.getElementById('select-packages');
const selectPieces = document.getElementById('select-pieces');


//add button event listener
buttonAdd.addEventListener('click', function() {
  // Get selected values from dropdowns
  const numDestinations = selectDestinations.selectedIndex; // Get the index of the selected option
  const getDestination = selectDestinations.options[numDestinations].text; // Get the text of the selected option

  const numPackages = selectPackages.selectedIndex;
  const getPackage = selectPackages.options[numPackages].text;

  const numPieces = selectPieces.selectedIndex;
  const getPiece = selectPieces.options[numPieces].text;

  const text = `${getDestination} - ${getPackage} - ${getPiece}`; // 並べたい順で1つの文字列にする

  // Create a new list item and append it to the list
  const newList = document.createElement('li');
  const labelSpan = document.createElement('span');
  labelSpan.textContent = text; //spanにtextを入れる=labelSpan内のtext以外には取消線が入らないようにするため
  // Create delete button
  const deleteButton = document.createElement('button');
  deleteButton.textContent = '削除';
  deleteButton.addEventListener('click', function() {
    list.removeChild(newList);
  });
  // create done button
  const doneButton = document.createElement('button');
  doneButton.textContent = '完了';
  doneButton.addEventListener('click', function() {
    labelSpan.style.textDecoration = 'line-through';

  // create timestamp
  const timeStamp = document.createElement('span');
    timeStamp.textContent = ` (${new Date().toLocaleString()})`;
    newList.appendChild(timeStamp);
  });

  // newList.appendChild(label);
  list.appendChild(newList);
  newList.appendChild(labelSpan);
  newList.appendChild(deleteButton);
  newList.appendChild(doneButton);
});

Point
・取消線の範囲特定のために書きコードを追加。

const labelSpan = document.createElement('span');

上記のコードを追加したので、
↓の一文を

  const newList = document.createElement('li');
    newList.textContent = text; 

↓に編集しました。

  const newList = document.createElement('li');
  const labelSpan = document.createElement('span');
    labelSpan.textContent = text; 

[8]Element/createElementの少し確認・おさらい

⭐︎ 「Element」とは?
Element=HTMLの中の 要素(タグ) のこと。
HTMLのあらゆる要素を表す基本クラス(抽象的な概念)のこと。
参考DOMツリー

Node
 └─ Element
     └─ HTMLElement
         ├─ HTMLDivElement      ← <div>
         ├─ HTMLSpanElement     ← <span>
         ├─ HTMLParagraphElement← <p>
         ├─ HTMLInputElement    ← <input>(value, checked など固有あり)
         └─ ...(他多数)

つまり、ものすごく省略すると
⭐︎ createElement(div) と記述すれば、
<div>タグを作ってね
createElement(li) と記述すれば
<li>タグを作ってね
という意味。

それをコードでは以下のように書いて使います。

const newList = document.createElement("li");
  • document.createElement():HTML要素を新しく作る

  • "li":作りたい要素の種類

  • newList:変数にその要素を代入しておく(後で操作するため)

[感想]

何度も同じことを学習して定着していく感覚をよく感じた回になりました。
JavaScriptの学習はApprenticeship始まってから2回目で、
「前回も同じような事を学習した。」と自覚しているポイントがいくつかあったのですが、
前回よりもより理解が素直になっているという感覚があります。
私は要領よく学習していけるタイプではないですが、確実に実力に変えていける様、学習を続けたいと思います。

注意
私はプログラミング学習歴1年未満の初学者です。
この記事は自身の備忘録用として掲載しております。
間違いがあるかと思いますので、今後の学習のためにコメントにご指摘を頂けますと幸いです。

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?