JavaScript LogoThe little-known JavaScript Option() constructor allows you to avoid the verbose syntax of creating DOM elements

We all love jQuery. Among the many awesome qualities of this library is the ability to easily create DOM elements and place them in the document without the normally verbose syntax of native JavaScript.

But there is a little-known feature of JavaScript that allows you to create option elements with fairly minimal effort. This feature is the Option() constructor. The syntax is simple:

  1. Get a reference to a form element
  2. Instantiate the constructor and associate the returned object with the form element
  3. During instantiation, pass-in the following arguments: 1) the text shown in the page [string], 2) the value of the control [string], 3) if it is the default selection [true/false] and if it is selected [true/false]

Example # 1

 

In Example # 1, we have a simple form that includes a select control. In the markup there are three options: “Monday”, “Tuesday” and “Wednesday”. When the JavaScript runs, the following actions take place:

  1. We get a reference to the select controls (“w”)
  2. We delete all of the option elements (w.length = 0)
  3. We create an array of objects, each with two properties (“d”)
  4. We loop through the array and for each array element, dynamically create a new select element, using the object’s “text” and “val” properties. In each case the last two arguments: “false”,”false” mean that this new element will not be the default, nor will it be selected.

And that’s it!

Summary

The little-known Option() constructor can be used to create new HTML option elements. So, depending on how you choose to approach this, you can write some pretty efficient code that side-steps the normally verbose syntax of document.createTextNode(), document.createElement(), and document.appendChild() methods.

Helpful Links for the JavaScript Option() constructor

http://www.coderanch.com/t/120551/HTML-CSS-JavaScript/Option-Constructor

http://www.devguru.com/technologies/ecmascript/quickref/option.html

http://msdn.microsoft.com/en-us/library/ie/dd757810(v=vs.85).aspx