add method

Adds an element to the areas, controlRange, or options collection.

Document Object Model (DOM) Level 2 HTML Specification, Section 1.6.5

 

Syntax

object.add(element, before)

Parameters

element [in]

Type: IHTMLElement

Object that specifies the element to add to the collection.
before [in, optional]

Type: Variant

Variant of type Integer that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.

Internet Explorer 8 and later. Variant of type Object that specifies an element to insert before, or null to append the object to the collection.

Return value

Type: HRESULT

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

Standards information

Remarks

Internet Explorer 8. In IE8 Standards mode, before also accepts an Variant of type Object that specifies the object before which to insert the element. For more information, see Defining Document Compatibility.

This method adds an option element to a select block.

Before you can add an element to a collection, you must create it first by using the createElement method.

Examples

This example uses the add method to insert an object into the options collection of a select object. In Internet Explorer, the option element must be added to the collection prior to setting properties.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/add.htm


<select id="oSelect">
    <option value="1">One</option>
</select>

<script type="text/javascript">
var oSelect = document.getElementById('oSelect');
var oOption = document.createElement('OPTION');
// Add the option to the collection first, then set properties
oSelect.options.add(oOption);
oOption.innerHTML = "Two";
oOption.value = "2";
</script>


Alternatively, you can achieve the same result with less code by using the array syntax of the options collection to append a new Option element.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/add.htm


<script type="text/javascript">
var opts = document.getElementById('oSelect').options;
opts[opts.length] = new Option("Three","3");
</script>


In Internet Explorer 8 and later, the add method supports the standard way of specifying an object as an insertion point. The following code inserts the new Option in front of another option element already in the control.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/add.htm


<meta http-equiv="X-UA-Compatible" content="IE=8"/>




<script type="text/javascript">
var sel = document.getElementById('oSelect');
sel.add(new Option("Four","4"), oOption);
</script>


See also

areas
controlRange
options
select
remove

 

 

Show:
© 2014 Microsoft