How to add a new option before the last choice?

I'm trying to create a new option on the fly, and then add it right before the last option.

When I use $("#select").append("<option>hi</option") , it is always added after the last.

How to add a new option before the last selection option?

+6
source share
4 answers
 $("select option:last").before("<option>hi</option>"); 

Online Demo: http://jsfiddle.net/6MVEd/

+12
source
 $("#select option").eq(-2).after("<option>hi</option") 

or

 $("#select option").eq(-1).before("<option>hi</option") 

"#select option" is a complete querySelectorAll selector.

+7
source

I believe you need a method . insertBefore () .

+3
source

http://jsfiddle.net/

 $("#select option:last").prev().append("<option>New Option</option>"); 

You might want to avoid using select as an identifier.

+1
source

Source: https://habr.com/ru/post/891506/


All Articles