Greetings all,
I've written a script to create HTML5 image captions from regular image tags using <figure>
and <figcaption>
.
My CMS uses FCKEditor, which always places embedded images inside of paragraphs. So my script builds a <figcaption>
around the image and then moves it outside of the paragraph (see html5, figure/figcaption inside a paragraph gives unpredictable output)).
The script I wrote works, but it traverses the DOM twice 'cause I couldn't figure out a way to traverse the DOM only once. I'd appreciate if someone better versed at JQuery could offer some suggestions on how to simplify/improve the script.
Thanks, -NorthK
// use like this:
// <img class="caption" src="http://placehold.it/350x150" alt="Sample image caption" />
//
$(document).ready(function() {
// iterate over each element with img.caption
$('img.caption').each(function() {
var classList = $(this).attr('class'); // grab the image's list of classes, if any
$(this).wrap('<figure class="' + classList + '"></figure>'); // wrap the <img> with <figure> and add the saved classes
$(this).after('<figcaption>' + $(this).attr('alt') + '</figcaption>'); // add the caption
$(this).removeAttr('class'); // remove the classes from the original <img> element
});
// now iterate over each figure.caption we built, and relocate it to before its closest preceding paragraph
$('figure.caption').each(function() {
$(this).parent('p').before($(this));
});
})