「jQuery」prependで要素内の先頭にタグを追加する

2022年3月14日

環境
jQuery 3.6.0
Google Chrome 99.0.4844.51

書式
$(セレクタ名).prepend(“<b>study</b>");
prependを使用して要素の後にタグを追加します。

使用例

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.0/jquery.min.js"></script>
<script>
$(function(){
// ボタンを押すと、要素の前にskillを追加する
$('#btnAdd').click(function(){
//要素の前にタグを追加する
$("#cft").prepend("<b>study</b>");
});
});
</script>
</head>
<body>
<p><input type="button" id="btnAdd" value="追加"></p>
<div id="cft"><span style="color:green;"> skill</span></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ // ボタンを押すと、要素の前にskillを追加する $('#btnAdd').click(function(){ //要素の前にタグを追加する $("#cft").prepend("<b>study</b>"); }); }); </script> </head> <body> <p><input type="button" id="btnAdd" value="追加"></p> <div id="cft"><span style="color:green;"> skill</span></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
  // ボタンを押すと、要素の前にskillを追加する
  $('#btnAdd').click(function(){
    //要素の前にタグを追加する
    $("#cft").prepend("<b>study</b>");
  });
});
</script>
</head>
<body>
  <p><input type="button" id="btnAdd" value="追加"></p>
  <div id="cft"><span style="color:green;"> skill</span></div>
</body>
</html>

実行結果
「追加」ボタンを押すと要素(skill)の前に要素(study)を追加します。

jQuery

Posted by arkgame