jQuery beforeで指定の要素の前に追加する
環境
jQuery 3.6.4
Windows 10 Home 64bit
構文
$(追加先).before(追加する要素)
beforeメソッドを使って、指定の要素の前に子要素を追加します。
使用例
$(“#ark1").before('<p id = “a1″>品川</p>’);とした場合、<div id="ark1">の前に<p id = “a1">品川</p>が追加されます。
サンプルコード
<!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(){
$("#ark1").before('<p id = "a1">品川</p>');
});
});
</script>
</head>
<body>
<div id="ark1">
<p id="p1">東京</p>
</div>
<button id="chk">追加</button>
</body>
</html>
実行結果
「追加」ボタンを押すと、要素「id="ark1″」の前に「<p id = “a1">品川</p>」を追加します。