Parent pages:
  1. Home
  2. Blog
  3. HTML comment as data container

HTML comment as data container

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

A comment is a separate DOM node, and its text content is available with standard property of any DOM node — nodeValue, or with data property of comment as DOMCharacterData object.

Unlike elements, comment has no identifier or class, so comment as DOM node can be accessed with one of methods that are common to all DOM nodes — for example, with previousSibling / nextSibling properties of a sibling node.

Example
<div id="example">“Base” element.</div><!--data that we need-->

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

This method allows avoid using attributes for purposes other than that intended (e.g., using title attribute to store a data that are not description of 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 of data stored in title attribute as tooltip that is pointless for user),
  • indexing service data by search engines and undesired displaying of the data in search results are prevented.