Suma Suma - 12 days ago 7
Javascript Question

Replicate HTML source of a DOM element in current state

On my page there are a few

<select>
html elements, each of them with multiple
<option>
values. I would like the same
<select>
elements to be used in a MapBox description toolkit, which expects me to pass a HTML source into its setHTML method.

The simple way I do it now is:

var tableOption = document.getElementById(selectId);
var html = tableOption.innerHTML;
return "<select>" + html + "</select>";


This works, however it has a drawback of passing the original html source, therefore it does not reflect which option is selected right now. I know I can get currently selected option with value or selectedIndex, and it should be possible to parse the HTML I have obtained and remove and add
selected
property to a corresponding node in JS, however this seems a bit complicated.

Is there some easier way how to get a HTML source which could be used to construct a copy of a
select
element with the exact selection state it has now?

I would prefer a solution without jQuery if possible.

Answer

You could just wrap your select in another element. Then you'd be able to select it by id, get the parent node, then the parent node's innerHTML. If you want to show which option is currently selected, you can place the selected attribute on it.

document.getElementById('selectId').addEventListener('change', function() {
    var opts = this.getElementsByTagName('option');
    for (var i = 0; i < opts.length; i++)
        opts[i].removeAttribute('selected');
    this.querySelector('option:checked').setAttribute('selected', 'selected');
    console.log(this.parentNode.innerHTML);
});
<div class="select-wrapper">
  <select id="selectId">
    <option>Yes</option>
    <option>No</option>
  </select>
</div>