jQuery beforeで指定の要素の前に追加する

環境
jquery3.6.3
Google Chrome 111.0.5563.65(Official Build)

書式
$(追加先).before(追加する要素)
before関数を使って指定の要素の前に追加します。

使用例

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.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function() {
$("#cft").before('<p id = "a2">tokyo</p>');
});
});
</script>
</head>
<body>
<div id="cft">
<p id="p2">あいうえお</p>
</div>
<input type="button" id="btnchk" value="変更">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnchk").click(function() { $("#cft").before('<p id = "a2">tokyo</p>'); }); }); </script> </head> <body> <div id="cft"> <p id="p2">あいうえお</p> </div> <input type="button" id="btnchk" value="変更"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
      $("#btnchk").click(function() {
        $("#cft").before('<p id = "a2">tokyo</p>');
      });
});
</script>
</head>
<body>

<div id="cft">
  <p id="p2">あいうえお</p>
</div>
<input type="button" id="btnchk" value="変更">

</body>
</html>

実行結果
ボタン「変更」を押すと、
$(“#cft").before('<p id = “a2″>tokyo</p>’);とした場合、
<div id="cft">の前に<p id = “a2">tokyo</p>が追加されます。

jQuery

Posted by arkgame