title: Find next element with a given class, regardless of where it appears in the DOM
body: <p>I'm having a really hard time trying to figure out something which I believe should be relatively simple.</p>
  
  <p><strong>I need to get the next occurrence of a class (div.content), which could appear anwhere in the DOM</strong></p>
  
  <p>Below is some simplified markup which represents what I have:  </p>
  
  <pre><code>&lt;div class="container"&gt;
    &lt;div class="content"&gt;
      Example content #1    &lt;a href="#" class="next"&gt;Next&lt;/a&gt;
    &lt;/div&gt;
  
    &lt;div class="content"&gt;
      Example content #2    &lt;a href="#" class="next"&gt;Next&lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;div class="container"&gt;
    &lt;div class="content"&gt;
      Example content #1    &lt;a href="#" class="next"&gt;Next&lt;/a&gt;
    &lt;/div&gt;
  
    &lt;div class="content"&gt;
      Example content #2    &lt;a href="#" class="next"&gt;Next&lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Showing the next <code>content</code> div within a given <code>container</code> works fine, the problem comes when I try to get from the <strong>last</strong> <code>content</code> div in a <code>container</code> to the <strong>first</strong> <code>content</code> div  in the next <code>container</code>.</p>
  
  <p>A couple of important points:-</p>
  
  <ul>
  <li><p>By default, <strong>only the first</strong> <code>content</code> div is visible, the rest are hidden, though I need a solution that would work if for instance the second <code>content</code> div in the fourth <code>container</code> is visible.</p></li>
  <li><p>Only one <code>content</code> div will ever be visible.</p></li>
  </ul>
  
  <p>The only solution I've managed to come up with so far seems extremely cumbersome, although it <em>does</em> work. </p>
  
  <pre><code>$('.next').click(function() {
      $theContent = $(this).parent('.content');
      $theContent.hide();
  
      if ($theContent.next('.content').length) {
          $theContent.next('.content').show();
      } else if ($theContent.parent('.container').next('.container')
          .children('.content').length
      ) {
          $theContent.parent('.container').next('.container')
              .children('.content:first').show();
      } else {
          // reached the end or something went wrong
      }
  });
  </code></pre>
  
  <p>The major downside to this is that it relies on having the above DOM structure, I'd convinced myself that a method would exist for selecting the next element with a given class, regardless of where it appeared in the DOM.</p>
  
  <p><strong>Ideally I'd like a solution which doesn't rely on any given DOM structure, if that's not possible, any alternative solutions would be helpful!</strong></p>
  
  <p><a href="http://jsfiddle.net/MgP6N/2/" rel="nofollow">Here's a fiddle with the above example</a></p>
  
  <p>Sorry for the long-winded question!</p>