jQuery – How to automatically display images with caption

The following jQuery shows a method I’ve used to automatically format images with a caption taken from the image ALT tag.

This method is useful where you can only insert images – without the ability to customise how images are formatted.

The jQuery should be loaded once the document is ready. It searches through the content for any images and wraps them in a “figure” element, then if the image has an ALT tag it adds a caption using the figcaption element.

For example:

Three Word documents titled "Ben" "Harry" and "James"
Three Word documents titled “Ben” “Harry” and “James”
jQuery('main#content article img:not( .no-figure )').each(function() {
    if (!jQuery(this).parent().is('figure')) {
        jQuery(this).wrap(jQuery('<figure/>', {
            'class': 'image'
        var img_alt = jQuery(this).attr('alt');
        if (img_alt) {