チェックした項目をリスト形式で表示したい

処理の順番を考えて実装してみましょう。
2020年4月7日
ユーザー

こんにちは、いつもわかりやすいレッスンありがとうございます。

チェックスボックス選択後にボタンを起動させた場合の処理について、

・red, yellow

のような形式ではなく、下記のようなリスト形式で表示させたいと思っています。

・red
・yellow

レッスンの配列で表示させるコードをアレンジして、ループ処理を加えて自分で作ってみたのですが、3つ選択した場合、画像のように赤3つ、黄2つ、青1つが表示されてしまい、うまく機能しません。どう操作すればリスト形式で表示できるのでしょうか。

下記ソースコードです。お手数をおかけしますが、ご教授いただければ幸いです。

main.js

'use strict';
{
  document.querySelector('button').addEventListener('click', () => {
    const colors = document.querySelectorAll('input');
    const selectedColors = [];
    let i;
    colors.forEach(color =>{
      // 配列に選択肢が入る
      if (color.checked === true) {
        selectedColors.push(color.value);
      }
    //配列を分解してリストに振り分
    for (i=0; i < selectedColors.length; i++) {
      let li = document.createElement('li');
      li.textContent = selectedColors[i];
      document.querySelector('ul').appendChild(li);
    }


    });

  });


}

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JS Basics</title>
  <style>
    .my-color {
      color: red;
      background-color: skyblue;

    }

    .my-border {
      border-bottom: 4px solid orange;
    }
  </style>
</head>
<body>
  <input type = 'checkbox' name = 'color' value ='red'>赤
  <input type = 'checkbox' name = 'color' value ='yellow'>黄
  <input type = 'checkbox' name = 'color' value ='blue'>青

  <button >Add</button>

  <ul>
  </ul>
  <h1 id = 'target' data-translation = "Dotinstall">ドットインストール</h1>

  <script src = "js/main.js"></script>
 </body>
</html>

この回答を見るにはプレミアムサービスへの登録が必要です

プレミアムサービスとは?