-1

I have a select element's options collection in JavaScript. I want to clone the whole list of items without using jQuery. How to do this?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Janardhan
  • 13
  • 6

2 Answers2

1

You can use Node.cloneNode()

let collection = document.querySelectorAll('option');
let cloned = Array.from(collection).map(option => option.cloneNode(true));
const select = document.querySelector('select');
cloned.forEach(opt=>{
  select.appendChild(opt)
})
<select>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
</select>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

This should clone and sort of data object, wont work if arrow methods are involved.

const clone = obj =>
  Array.isArray(obj)
    ? obj.map(item => clone(item))
    : obj instanceof Date
    ? new Date(obj.getTime())
    : obj && typeof obj === 'object'
    ? Object.getOwnPropertyNames(obj).reduce((o, prop) => {
        o[prop] = clone(obj[prop]);
        return o;
      }, {})
    : obj;
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60