LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】テキストボックスに「リンク名」と「URL」を入力しボタンをクリックすると、入力されたリンク名とリンク先URLが設定されたa要素を追加するプログラムを作成

Last updated at Posted at 2021-05-11

image.png

<!DOCTYPE html>
  <html lang="ja">
      <head>
          <meta charset="UTF-8">
          <title>8-5 課題</title>
          <script>
          function add_element(){
//-------------リンク名とURLのIDを取得----------------------------------------------------
             var inputText = document.getElementById("txt").value;     //#txtの値を取得 テキストボックスの値
             var inputUrl  = document.getElementById("url").value;     //#urlの値を取得
//-------------------------------------------------------------------------------------
//-------------<a>要素を作成------------------------------------------------------------
             var element_a = document.createElement('a');       
//-------------------------------------------------------------------------------------
             element_a.innerHTML = inputText;   // テキストを指定 txtのid
             element_a.href      = inputUrl;    //<a>タグのURLを指定  urlのid
//-------------output要素のIDを取得----------------------------------------------------
             var output = document.getElementById('output');
//-------------------------------------------------------------------------------------
//-------------output要素にリンクを挿入-------------------------------------------------
             output.appendChild(element_a);   //アペンドチャイルド   aタグがoutputのidの子供の要素として追加
//-------------------------------------------------------------------------------------
          }
//-----------javascriptの開始----------------------------------------------------------
          window.onload = function(){
//-------------addのIDを取得-------------------------------------------------------------
              var add = document.getElementById("add");
//-------------------------------------------------------------------------------------
//---------------リンク追加ボタンを押下することで、イベント発火、add_element関数を実行---------------
              add.addEventListener('click',add_element,false);
//-------------------------------------------------------------------------------------
          }
          </script>
      </head>
      <body>
         <form>
              リンク名:
              <input type="text" id="txt" >
              URL:
              <input type="text" id="url" >
              <button id ="add" type="button" >リンク追加</button> 
         </form>
          <!-- ------------------------------------------------------- -->
          <div>
             <p id="output"></p>
          </div>
      </body>
          <!-- ------------------------------------------------------- -->
  </html>

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