对于选择的DOM对象,add()和appendChild()是否相同? [英] Are add() and appendChild() the same for select DOM objects?
问题描述
我想知道如果appendChild()和add()都是在JavaScript中选择DOM对象完成相同的任务?
var someSelect = document.getElementById (选择列表);
var newOption = document.createElement('option');
someSelect.appendChild(newOption);
//以上与以下相同?
someSelect.add(newOption);
在这种情况下,我相信他们会完成任务。
add()
是通过 HTMLSelectElement
界面专门为选择
元素,并有一些额外的选项(例如添加新的选项
的可选索引等)。
appendChild()
将给你一个直接附加的子节点。
注意两种方法跨浏览器的不同实现:我认为这将是您最大的痛点。 IIRC,当将孩子附加到选择
s时,IE会导致问题,因此如果该方法存在,您可能需要添加
并退回 appendChild
。
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);
In this case, I believe they would accomplish 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 select
s, so you might want to add
if that method exists and fall back on appendChild
.
这篇关于对于选择的DOM对象,add()和appendChild()是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!