title: Simplest way to tab only through focusable descendants of a particular element?
body: <p>Let's say I have a document full of focusable elements, either because they are innately focusable (like <code>&lt;input type="text"&gt;</code>) or because they have <code>tabindex="0"</code> or the like.</p>
  
  <p>Now let's say there's a section of my document that I want to display as a modal dialog box, and I don't want the user to be distracted by anything outside the dialog box. I would like for the tab key to cycle only through focusable elements inside the container element for the dialog box. What is the simplest way to do this?</p>
  
  <p>If possible, I am looking for a solution that doesn't care what the contents of the dialog or the rest of the page are and doesn't try to modify them. That is, I don't want to make the elements outside of the dialog not focusable, for example. First, this requires making a reversible change and keeping track of state. Second, this requires knowing all the possible ways an element could be made focusable. This feels messy, fragile, and unscalable to me.</p>
  
  <p>My first attempt looks like this, but works only in the forward direction (pressing Tab). It doesn't work in the reverse direction (pressing Shift+Tab).</p>
  
  <pre><code>&lt;div&gt;Focusable stuff outside the dialog.&lt;/div&gt;
  &lt;div class="dialog" tabindex="0"&gt;
    &lt;!-- Focus should be trapped inside this dialog while it's open --&gt;
    &lt;div class="content"&gt;
      Form contents and focusable stuff here.
    &lt;/div&gt;
    &lt;div class="last-focus" tabindex="0" onfocus="this.parentNode.focus()"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div&gt;More focusable stuff outside the dialog.&lt;/div&gt;
  </code></pre>
  
  <p>I'd rather see pure JavaScript solutions. If there is a means of doing this with a library such as jQuery, I would prefer a link to the library code that does this.</p>