1

I have a variable containing the options of a select element:

var allOptions = document.getElementById('ddl').options;

When I am removing the options

var selector = document.getElementById('ddl');
selector.options.length = 0;

the options in allOptions are also removed.

How can I avoid that?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • impossible to say what you are asking here – Mihai Iorga Aug 24 '12 at 14:06
  • 1
    You need to clone the object, see http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object – Barmar Aug 24 '12 at 14:06
  • 3
    No, it makes sense. He gets a _reference_ to `options` and later changes `options.length` from a seemingly different place... and he doesn't understand why... – canon Aug 24 '12 at 14:07

1 Answers1

2

You could use cloneNode to create an exact copy of the original select node. This way, you can safely clean the dropdown without affecting the variable that holds the original options:

var originalOptions = document.getElementById('ddl').cloneNode(true).options;

DEMO.

João Silva
  • 89,303
  • 29
  • 152
  • 158