对于选择的 DOM 对象,add() 和appendChild() 是否相同?
我正在开发一个小型网络应用程序,该应用程序可以更改选择下拉列表的内容。
我想知道appendChild()和add()是否都在JavaScript中的选择DOM对象上完成相同的任务?
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 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,我相信他们会完成同样的任务。
add( )
是专门通过HTMLSelectElement
接口专门用于向select
元素添加选项,并且有一些额外的选项(例如用于添加新的可选索引)选项
等)。appendChild( )
将为您提供子节点的直接追加。注意两种方法跨浏览器的不同实现:我认为这将是您最大的痛点。 IIRC,IE 在将子项附加到
select
时会导致问题,因此如果该方法存在,您可能需要add
并依靠appendChild
。In this case, I believe they would accomplish the same task.
add( )
is provided specially via theHTMLSelectElement
interface specifically to add options to aselect
element and has a few extra options (such as an optional index at which to add the newoption
, 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
select
s, so you might want toadd
if that method exists and fall back onappendChild
.如果您想在操作
If you want to be sure of cross-browser compatibility when manipulating options within a
<select>
, the surest way is to use itsoptions
property and populate it withOption
objects. The following time-honoured method works in all scriptable browsers since the late 1990s:我认为它应该是等效的,但是在这里您可以找到一个问题,当您尝试使用选项组时,它会说明不同的实现:
选择框:在 IE 上,项目被添加到 OptGroup 而不是 root。 FF ok
当 select 元素内已有组时,IE 无法在“根”中添加新选项。
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.