LoginSignup
0
0

More than 1 year has passed since last update.

項目を表示する

Posted at

配列を作成する

  <script>
      'use strict';
      let todo = ['デザインカンプ作成', 'データ整理', '勉強会申し込み', '牛乳買う'];
      for(let item of todo) {
          console.log(item);
      }
  </script>
for(let item of todo){

気づき

対象となる配列todoから一つずつ取り出し、変数itemに代入されるのか。
取り出される限り繰り返されるのか。

console.log(item);

気づき

代入された変数をconsoleオブジェクトに表示させるのか。

項目を追加する

  <script>
      'use strict';
      let todo = ['デザインカンプ作成', 'データ整理', '勉強会申し込み', '牛乳買う'];
      todo.push('歯医者に行く');
      for(let item of todo) {
          console.log(item);
      }
  </script>
todo.push('歯医者に行く');

気づき

配列todoの最後に追加される。

puthメソッド

このpush()メソッドは、配列の末尾に 1 つ以上の要素を追加し、配列の新しい長さを返します。

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
出典

項目一つひとつを<li>~<li>で囲む

  <script>
      'use strict';
      let todo = ['デザインカンプ作成', 'データ整理', '勉強会申し込み', '牛乳買う'];
      todo.push('歯医者に行く');
      for(let item of todo) {
          const li = `<li>${item}<li>`;
          console.log(li);
      }
  </script>

コンソール

<li>デザインカンプ作成<li>
<li>データ整理<li>
<li>勉強会申し込み<li>
<li>牛乳買う<li>
<li>歯医者に行く<li>

気づき

こんなことまでできるのか。
すごいな。
HTMLに出力できるのではないか?

項目をHTMLに表示する

  <script>
      'use strict';
      let todo = ['デザインカンプ作成', 'データ整理', '勉強会申し込み', '牛乳買う'];
      todo.push('歯医者に行く');
      for(let item of todo) {
          const li = `<li>${item}<li>`;
          console.log(li);
          document.getElementById('list').insertAdjacentHTML('beforeend', li);
      }
  </script>
document.getElementById('list').insertAdjacentHTML('beforeend', li);

気づき

documentオブジェクトに対してidがlistの要素を丸ごと取得。
insertAdjacentHTML()メソッドで定数liを追加する

Element.insertAdjacentHTML()

insertAdjacentHTML()インターフェイスのメソッドは 、Element指定されたテキストを HTML または XML として解析し、結果のノードを DOM ツリーの指定された位置に挿入します。

出典

insertAdjacentHTMLメソッドとinnerHTMLプロパティの違い

HTMLの要素を編集するメソッドには、他にinnerHTMLというプロパティもあります。

innerHTMLはHTMLを上書きするために使います。
insertAdjacentHTMLは要素の追加のために使います。

出典

出典

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