-2

Using jquery (or native js). How do I get all the options html in a list, so the output is something like:

var options = ['<option value="" selected="">---------</option>', <option value="1">Option 1</option>']
Yunti
  • 6,761
  • 12
  • 61
  • 106

2 Answers2

2

You can get the select node and find all the options in the select node and get the html from those options.

var selectNode = $('select-selector');
var options = selectNode.find('option').toArray().map(function (o) { return o.outerHTML});

Edit as per suggestion from comment by Rory.

$.map(selectNode.find('option'), function(o) { return o.outerHTML; });
Brijesh Bhakta
  • 1,280
  • 1
  • 8
  • 14
0

Something like this?

var selectBoxEl = document.getElementById('selectBox');
var arrayOfNodes = selectBoxEl.childNodes;
var optionsArr = [];
// loop through child Nodes and only get option nodes
for (var i = 0; i < arrayOfNodes.length; i++) {
 if (arrayOfNodes[i].nodeName === 'OPTION') {
   optionsArr.push(arrayOfNodes[i].outerHTML);
  }
}

console.log(optionsArr);
<select id="selectBox">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Anthony
  • 1,439
  • 1
  • 19
  • 36