「jQuery」.prependで指定要素の先頭にhtmlタグを追加する
環境
jQuery3.6.0
Google Chrome 98.0.4758.102
書式
$(“セレクタ名").prepend(“html要素");
prependを使用して要素の後にタグを追加します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function(){
//ボタンを押すと、要素の前に「東京」を追加する
$('#btnReg').click(function(){
//要素id="cft"の前にタグを追加する
$("#cft").prepend("<b>東京</b>");
});
});
</script>
</head>
<body>
<div id="cft"><span style="color:red;">tokyo</span></div>
<p><input type="button" id="btnReg" value="追加"></p>
</body>
</html>
結果
「追加」ボタンを押すと、要素「id="cft"」の前に「東京」を追加します。