jQuery prependで指定の要素の子要素の先頭に追加する

環境
jQuery 3.6.4
Windows 10 Home 64bit

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

使用例
$(“#cft3").prepend('<p id = “p3″>東京</p>’);とした場合、
<div id="cft3">の子要素の先頭に<p id = “p3">東京</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(){
$("#cft3").prepend('<p id="cft3">東京</a>');
});
});
</script>
</head>
<body>
<div id="cft3">
<p id="p3">tokyo</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(){ $("#cft3").prepend('<p id="cft3">東京</a>'); }); }); </script> </head> <body> <div id="cft3"> <p id="p3">tokyo</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(){
     $("#cft3").prepend('<p id="cft3">東京</a>');
  });
});
</script>
</head>
<body>

<div id="cft3">
  <p id="p3">tokyo</p>
</div>
<button id="chk">追加</button>
</body>
</html>

実行結果
「追加」ボタンを押すと、要素「id="p3″」の先頭に子要素「<p id = “p3">東京</p>」を追加します

jQuery

Posted by arkgame