「jQuery」セレクトボックス(select)要素のoptionを削除する方法

2021年8月11日

htmlコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<select name="mk">
<option></option>
<option value="10">AA</option>
<option value="11">BB</option>
<option value="13">CC</option>
</select>
<select name="mk"> <option></option> <option value="10">AA</option> <option value="11">BB</option> <option value="13">CC</option> </select>
<select name="mk">
  <option></option>
  <option value="10">AA</option>
  <option value="11">BB</option>
  <option value="13">CC</option>
</select>

JSコード
1.最初の要素を削除
方法1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var cft = $('select[name=mk]');
cft.children('option:first-child').remove();
var cft = $('select[name=mk]'); cft.children('option:first-child').remove();
var cft = $('select[name=mk]');
cft.children('option:first-child').remove();

方法2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var cft = $('select[name=mk]');
cft.children().first().remove();
var cft = $('select[name=mk]'); cft.children().first().remove();
var cft = $('select[name=mk]');
cft.children().first().remove();

2.指定のn番目のoptionを削除
書式
変数名.children('option:nth-child(n番目)’).remove();

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var cft = $('select[name=mk]');
cft.children('option:nth-child(4)').remove();
var cft = $('select[name=mk]'); cft.children('option:nth-child(4)').remove();
var cft = $('select[name=mk]');
cft.children('option:nth-child(4)').remove();

3.最後の要素を削除
方法1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var cft = $('select[name=mk]');
cft.children('option:last-child').remove();
var cft = $('select[name=mk]'); cft.children('option:last-child').remove();
var cft = $('select[name=mk]');
cft.children('option:last-child').remove();

方法2

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var cft = $('select[name=mk]');
cft.children().last().remove();
var cft = $('select[name=mk]'); cft.children().last().remove();
var cft = $('select[name=mk]');
cft.children().last().remove();

 

jQuery

Posted by arkgame