jQuery eachとappendメソッドでリスト要素を追加するサンプル

環境
Google Chrome 106.0.5249.119
Windows 10 Home 64bit
jQuery 3.6.0

構文
1.複数のリスト要素を取得します
$('セレクター名 li’)

2.リスト要素毎にテキストを取得し、リスト要素を追加します
$('セレクター名’).append('<li>’+$(this).text()+'</li>’);

3.eachの基本構文
$('セレクター名 li’).each(function() {処理コード
objectの要素それぞれに対して、同じ処理を繰り返してくれます。

使用例

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>
$(document).ready(function(){
$('#btnadd').click(function(){
$('.cft li').each(function() {
$('.cft').append('<li>' +$(this).text()+'</li>');
});
});
});
</script>
</head>
<body>
<ul class="cft">
<li>tokyo</li>
<li>oosaka</li>
</ul>
<button id="btnadd">実行</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $('#btnadd').click(function(){ $('.cft li').each(function() { $('.cft').append('<li>' +$(this).text()+'</li>'); }); }); }); </script> </head> <body> <ul class="cft"> <li>tokyo</li> <li>oosaka</li> </ul> <button id="btnadd">実行</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('#btnadd').click(function(){
    $('.cft li').each(function() {
        $('.cft').append('<li>' +$(this).text()+'</li>');
    });
});
});
</script>
</head>
<body>
<ul class="cft">
  <li>tokyo</li>
  <li>oosaka</li>
</ul>
<button id="btnadd">実行</button>
</body>
</html>

結果
「実行」ボタンを押すと、「tokyo」、「oosaka」をリストに追加します。

jQuery

Posted by arkgame