Recently, I discussed the pitfalls of using custom HTML attributes and “expando” DOM properties to store per-element data. Thanks to the comments on that post I now understand that doing so is sometimes hard to avoid. Some people resort to using jQuery’s “metadata” plugin which can massively simplify the process of adding metadata (i.e. data about data). I’ve been meaning to post a technique I’ve been using recently; keeping data in HTML comments and then extracting it and tying it to the closest (parent) element.

With this technique you can do the following:

<div id="foo">
    <!-- { someData: 123, aString: "bar" } -->
    <p> ... regular content ... </p>
</div>
 
<!-- Regular comments can still be used -->
 
<p><!--{specialID:1234}-->... comment-data is tied to the parent element...</p>

Using the “commentData” function you can extract that information and use it within your JavaScript, e.g.

var foo = document.getElementById('foo');
 
var fooData = commentData( foo ); // => {someData: 123, aString: "bar"}
fooData.someData; // <= 123

Download “commentData” from Github

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!