第13章 jQuery - 要素を追加する
jQuery(ジェイクエリー)は、ウェブブラウザ用のJavaScriptコードをより容易に記述できるようにするために設計されたJavaScriptライブラリである。
homepage
# jQuery - 要素を追加する *** jQueryを使用すると、新しい要素/コンテンツを簡単に追加できます。 新しいHTMLコンテンツを追加するために使用される4つのjQueryメソッドを見ていきます。 * `append()` - 選択した要素内の末尾に要素を挿入します * `prepend()` - 選択した要素内の先頭に要素を挿入します * `after()` - 選択した要素外の後に任意のHTML要素を挿入します * `before()` - 選択した要素外の前に任意のHTML要素を挿入します ## append()メソッド jQuery `append()`メソッドは、選択したHTML要素の最後にコンテンツを挿入します。 #### 例 [sample13-1.html] ``` <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>Appended text</b>."); }); $("#btn2").click(function(){ $("ol").append("<li>Appended item</li>"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1">Append text</button> <button id="btn2">Append list items</button> </body> </html> ``` #### 実行結果 <!DOCTYPE html> <pre><span class="nocode"> <iframe src="javascript: '<html><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>Appended text</b>."); }); $("#btn2").click(function(){ $("ol").append("<li>Appended item</li>"); }); }); </script> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1" style="font-size:inherit">Append text</button> <button id="btn2" style="font-size:inherit;margin-left:10px">Append list items</button> </body> </html>'" width="800" height="250"></iframe> </span> </pre> *** > **練習** >> **問題**[Ex13-1.html] メソッドprepend()、after()を練習しましょう。 <!DOCTYPE html> <pre><span class="nocode"> <iframe src="javascript: '<html><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").after(" <b>Appended text</b>."); }); $("#btn2").click(function(){ $("ol").prepend("<li>Appended item</li>"); }); }); </script> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1">after text</button> <button id="btn2">prepend list items</button> </body> </html>'" width="800" height="300"></iframe> </span> </pre>
content
戻る