Initial Data on Elements

Exploiting JS for fun, profit, and fast renders.

by David Iglesias

HTML

<div id="view_with_extra_data"></div>

CSS

.monospace {
  border: 1px solid #aaa;
  background: #eee;
  border-radius: 3px;
  padding: 10px;
  font-family: monospace;
  color: #000;
  white-space: pre;
}

JavaScript

let view = document.querySelector('#view_with_extra_data');
view.initialData = {
  key: 'value',
  another: ['array', 'of', 4, 'values'],
  nested: {
    objects: ['are', {
      supported: true,
    }],
  }
};

// Now do things with the view...
renderView(view);

function renderView(element) {
  // Take element and do things with it...
	element.classList.add('monospace');
  element.innerText = JSON.stringify(element.initialData, null, 2);
}