Although it should be avoided in most cases sometimes it is necessary to create markup with JavaScript.  General best practices say that we keep our markup, styles and functionality separate whenever possible. However if it is a small enough element such as a tooltip I am generally fine with creating a div for it when it is needed dynamically.

Back on topic, it is not uncommon to see the creation of HTML using jQuery. We may see something like this:

$('<div>Tooltip text goes here!</div>').insertAfter('a.hint');

This is valid and works however if the complexity in increased even slightly by adding a class the readability suffers. Also if one uses double-quotes with their jQuery selector $("") then the “” in class="tooltip" would also have to be escaped:

$("<div class=\"tooltip\">Tooltip text goes here!</div>").insertAfter('a.hint');

So one can immediately see how if this is expanded any further it can be very difficult to follow. So a much better way to create the above would be similar but done in segments using jQuery’s functions/properties:

$('<div\>'Tooltip text goes here!</div>").insertAfter('a.hint');

This is great and proves that we can break out the different properties and chain them to our newly created HTML element. However this can be further streamlined by setting all those properties in an object:

		class: 'tooltip',
		text: 'Tooltip text goes here!'	

The following HTML will be the result:

<div class="tooltip">Tooltip text goes here!</div>