A little-known method is the element.insertAdjacentHTML
. With this method (supported by all major browsers, including IE 4), you can take an arbitrary HTML string, and insert it anywhere in the document.
To illustrate the power of the method, let's use your example...:
$("#my_id").before('<span class="asterisk">*</span>');
Becomes
document.getElementById('my_id').insertAdjacentHTML('beforebegin',
'<span class="asterisk">*</span>');
insertAdjacentHTML
's first argument determines the insertion position. Here's a comparison with jQuery:
As you can see, it's very easy to use. Assuming that the jQuery selector returns only one element, you can in general use document.querySelector
, but in this specific case, using document.getElementById
is more efficient.