jQuery lastメソッドでselect要素の最後のoptionを削除する

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.0

書式
1.select要素を取得します
var 変数名= $('select[name=セレクトボックスのname名]’);
2.select要素の最初のoptionを削除します
変数名.children().last().remove();
last()を使用することで、要素の中に存在する最後の要素だけを取り出して削除します。

使用例

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btns").click(function(){
  var sb = $('select[name=city]');
  //select要素の最後のoptionを削除する
   sb.children().last().remove();
  });
});
</script>
</head>
<body>

<select name="city">
  <option value="tokyo">東京</option>
  <option value="oosaka">大阪</option>
  <option value="fukuoka">福岡</option>
</select><p>
<input type="button" id="btns" value="削除"></p>
</body>
</html>

実行結果
「削除」を押すと、select要素の最後のoption「福岡」を削除します。

jQuery

Posted by arkgame