jQuery afterで指定の要素の後に追加する

環境
jQuery 3.6.4
Windows 10 Home 64bit

構文
$(追加先).after(追加する要素)
afterメソッドを使って指定の要素の後に子要素を追加します。

使用例
$(“#akr2").after('<p id = “a2″>品川</p>’);とした場合、<div id="akr2"></div>の後に<p id = “a2">品川</p>が追加されます。

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#chk").click(function(){
$("#ark2").after('<p id = "a2">品川</p>');
});
});
</script>
</head>
<body>
<div id="ark2">
<p id="p2">東京</p>
</div>
<button id="chk">追加</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function(){ $("#chk").click(function(){ $("#ark2").after('<p id = "a2">品川</p>'); }); }); </script> </head> <body> <div id="ark2"> <p id="p2">東京</p> </div> <button id="chk">追加</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#chk").click(function(){
      $("#ark2").after('<p id = "a2">品川</p>');
  });
});
</script>
</head>
<body>

<div id="ark2">
  <p id="p2">東京</p>
</div>
<button id="chk">追加</button>
</body>
</html>

実行結果
「追加」ボタンを押すと、要素「id="p2″」の後ろに「<p id = “a2">品川</p>」が追加されます。

jQuery

Posted by arkgame