[Javascript] deleting all options

Paul Novitski paul at novitskisoftware.com
Wed Feb 1 10:18:07 CST 2006


At 04:20 AM 2/1/2006, Nick Fitzsimons wrote:
> > now i need ans easy function to clear the <select> of all its options.
> >
> > do i have to count through every option of that select or is there a
> > faster way?
>
>you can use
>
>// remove all children of element
>while (element.firstChild) {
>    element.removeChild(element.firstChild);
>}


Nick, the method you illustrate is the best & safest as far as I 
know, and is documented here:
http://developer.mozilla.org/en/docs/DOM:element.removeChild

It's worth noting that it's possible, if not ideal, to use
         obj.innerHTML = "";
to destroy an element's contents including child nodes.

My personal experience with modifying the DOM with innerHTML is that, 
while it lets me insert raw HTML into the document, the DOM seems 
unaware of the elements implied by the markup, so it's NOT a easy 
shortcut to creating & appending child nodes.  I sometimes use it to 
delete markup but never to insert it -- unless I don't need to read 
or manipulate the elements in the markup I'm inserting.

I wonder if this blindness of the DOM to markup inserted using 
innerHTML is one of the 'widely differing implementations' we're 
warned against:
___________________________

innerHTML sets or gets all of the markup and content within a given element
...
Though not actually a part of the W3C DOM specification, this 
property provides a simple way to completely replace the contents of 
an element. For example, the entire contents of the document body can 
be deleted by:

document.body.innerHTML = "";  // Replaces body content with an empty string.
...
As there is no public specification for this property, 
implementations differ widely. It should never be used to write parts 
of a table - W3C DOM methods should be used for that - though it can 
be used to write an entire table or the contents of a cell.

ref: http://developer.mozilla.org/en/docs/innerHTML
___________________________

Paul 




More information about the Javascript mailing list