Create DOM Structure With innerHTML

From GreaseSpot
Jump to: navigation, search

The nonstandard setter method .innerHTML can be used to concisely create DOM structure in trivial user scripts.

function htmlToDomNode(html) {
  var container = document.createElement('div');
  container.innerHTML = html;
  return container.firstChild;
}

So, for a simple example, adding content can just be:

document.body.appendChild(
  htmlToDomNode('<span style="color: red">END OF PAGE</span>')
);

This approach can be used to .addEventListener() on the element, before adding it into the document.

Caveat: Content Type

Note: .innerHTML is sensitive to document.contentType. When the type is text/plain the .innerHTML setter does not create a structure of DOM nodes, but instead returns #text nodes. .innerHTML works for types such as text/html or application/xhtml+xml but where and how it works is undocumented.

Caveat: Tables

.innerHTML cannot be used to create parts of a TABLE.

Will work:

// An entire table works.
htmlToDomNode('<table><tr><td> ... </td></tr></table>');

Will not work:

htmlToDomNode('<tr><td> ... </td></tr>');
htmlToDomNode('<td> ... </td>');

So, if a script builds a table from a HTML string, it has to be done as a whole rather than in parts.

See: [1]

Personal tools