I was using the code below from this answer
var myOpts = document.getElementById('yourselect').options;
console.log(myOpts);
//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:
$('#yourselect').empty();
console.log(myOpts);
//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?
It's a reference to the actual object in the DOM by design. You can clone it by using <elem>.cloneNode()
, and storing that in a variable.
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> </select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.