jQuery – Perform function in same div as function caller
<p>I am really new to jQuery (and javascript).
I have 2 duplicated "editors" and I want to perform functions on a paragraph contained in the same div as the function caller.</p>

<p>I'm using the <code>closest</code> method to find the paragraph but I am not sure it is the best solution. Doing something with the index of the elements would be better?</p>

<p>Also, I'd like to give context to the selector to reduce the amount of DOM traversed.</p>

<p>A simplified version of the markup:</p>

<pre><code>&lt;div id="wrapper1"&gt;
  &lt;div&gt;
    &lt;p class="paragraph"&gt;This is text of box #1&lt;/p&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;div&gt;
      &lt;a href="#" class="doBold"&gt;Bold&lt;/a&gt;
      &lt;a href="#" class="doItalic"&gt;Italic&lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;div id="wrapper2"&gt;
  &lt;div&gt;
    &lt;p class="paragraph"&gt;This is text of box #2&lt;/p&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;div&gt;
      &lt;a href="#" class="doBold"&gt;Bold&lt;/a&gt;
      &lt;a href="#" class="doItalic"&gt;Italic&lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>A simplified version of the jQuery:</p>

<pre><code>  $(document).ready(function($){

  var methods = {
    doBold: function () { $(this).closest(':has(.paragraph)').toggleClass('bold') },
    doItalic: function () { $(this).closest(':has(.paragraph)').toggleClass('italic') },
    }

  $('.doBold').click(methods.doBold);
  $('.doItalic').click(methods.doItalic);
  });
</code></pre>
