I'm working on a small web application that changes the contents of a select drop-down.
I was wondering if appendChild() and add() both accomplish the same task on a select DOM object in JavaScript?
var someSelect = document.getElementById('select-list');
var newOption = document.createElement('option');
someSelect.appendChild(newOption);
// The above is the same as the following?
someSelect.add(newOption);
If you want to be sure of cross-browser compatibility when manipulating options within a <select>
, the surest way is to use its options
property and populate it with Option
objects. The following time-honoured method works in all scriptable browsers since the late 1990s:
var options = select.options;
options[options.length] = new Option("Option text", "option_value");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With