HTML comment as data container

Regular HTML comment can be used as a container to store text data intended to be displayed dynamically with JavaScript.

A comment itself is a regular DOM node, and its text content is available via the standard property of any DOM node — nodeValue, or via the data property of the comment as a CharacterData object.

Unlike elements, a comment cannot have an identifier or a class, so the comment as a DOM node can be accessed with one of ways common to all DOM nodes — for example, with the firstChild property of its parent element or with the previousSibling / nextSibling properties of a sibling node:

<div id="example"><!--data we need--></div>

<script>
var comment = document.getElementById('example').firstChild;
alert(comment.data);
</script>

This technique allows to avoid using attributes for purposes other than that intended (e. g. using the title attribute to store data that are not a description of the element), as well as using nonstandard attributes or need for creating hidden elements (e. g. DIV), which content, by the way, is perfectly indexed by search engines.

As a result:

  • HTML code is perfectly valid,
  • there are no undesired visual effects (e. g. displaying data stored in title attribute as a tooltip pointless for user),
  • indexing service data by search engines and undesired displaying of the data in search results are prevented.