leofontes leofontes - 3 years ago 81
Javascript Question

Javascript DOM variable is reference instead of copy

I was using the code below from this answer

var myOpts = document.getElementById('yourselect').options;
//prints HTMLOptionsCollection [ <option>, <option>, <option>, <option>, <option> ]

Now, after I had already stored the contents of the select in the variable, I used jQuery to empty the select using:

//prints HTMLOptionsCollection { length: 0, selectedIndex: -1 }

And to my surprise, the variable was empty as well.
My understanding was that the variable was a copy, not a reference to the DOM element.

Why does this behavior happen? And is there any way I can prevent it?

Answer Source

Simple way to accomplish both is use jQuery detach()

var $opts = $('#mySelect option').detach();

console.log('Stored options =', $opts.length)
console.log('Active options =',  $('#mySelect option').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
  <option value="4">Item 4</option>
  <option value="5">Item 5</option> 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download