Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are add() and appendChild() the same for select DOM objects?

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);
like image 307
kevin628 Avatar asked Dec 28 '22 08:12

kevin628


1 Answers

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");
like image 177
Tim Down Avatar answered Dec 31 '22 01:12

Tim Down