最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Are add() and appendChild() the same for select DOM objects? - Stack Overflow

programmeradmin3浏览0评论

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 acplish 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);

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 acplish 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);
Share Improve this question asked Aug 31, 2010 at 17:34 kevin628kevin628 3,5264 gold badges31 silver badges44 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

In this case, I believe they would acplish the same task.

add( ) is provided specially via the HTMLSelectElement interface specifically to add options to a select element and has a few extra options (such as an optional index at which to add the new option, etc.).

appendChild( ) will give you a straight append of the child node.

Watch out for different implementations of both methods cross-browser: I think that would be your biggest pain point. IIRC, the IEs would cause problems when appending children to selects, so you might want to add if that method exists and fall back on appendChild.

If you want to be sure of cross-browser patibility 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");

I think it should be equivalent, but here you can find a question which remarks the different implementations when you try to work with option groups:

SELECT box: On IE item is added to OptGroup instead of root. FF ok

IE fails to add a new option "in the root" when there is already group inside the select element.

发布评论

评论列表(0)

  1. 暂无评论