Suma Suma - 1 year ago 99
Javascript Question

Replicate HTML source of a DOM element in current state

On my page there are a few

html elements, each of them with multiple
values. I would like the same
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
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
element with the exact selection state it has now?

I would prefer a solution without jQuery if possible.

Answer Source

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++)
    this.querySelector('option:checked').setAttribute('selected', 'selected');
<div class="select-wrapper">
  <select id="selectId">

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