title: using .each() to iterate over selections for HTML5 <figure> and <figcaption>
body: <p>Greetings all,</p>
  
  <p>I've written a script to create HTML5 image captions from regular image tags using <code>&lt;figure&gt;</code> and <code>&lt;figcaption&gt;</code>.</p>
  
  <p>My CMS uses FCKEditor, which always places embedded images inside of paragraphs. So my script builds a <code>&lt;figcaption&gt;</code> around the image and then moves it outside of the paragraph (see <a href="https://stackoverflow.com/questions/5163294/html5-figure-figcaption-inside-a-paragraph-gives-unpredictable-output">html5, figure/figcaption inside a paragraph gives unpredictable output</a>)).</p>
  
  <p>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.</p>
  
  <p>Thanks,
  -NorthK</p>
  
  <pre><code>// use like this: 
  // &lt;img class="caption" src="http://placehold.it/350x150" alt="Sample image caption" /&gt;
  //
  $(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('&lt;figure class="' + classList + '"&gt;&lt;/figure&gt;'); // wrap the &lt;img&gt; with &lt;figure&gt; and add the saved classes
      $(this).after('&lt;figcaption&gt;' + $(this).attr('alt') + '&lt;/figcaption&gt;'); // add the caption
      $(this).removeAttr('class'); // remove the classes from the original &lt;img&gt; 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));
  });
  })
  </code></pre>