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.
I’m using the closest 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?
Also, I’d like to give context to the selector to reduce the amount of DOM traversed.
A simplified version of the markup:
<div id="wrapper1">
<div>
<p class="paragraph">This is text of box #1</p>
</div>
<div>
<div>
<a href="#" class="doBold">Bold</a>
<a href="#" class="doItalic">Italic</a>
</div>
</div>
</div>
<div id="wrapper2">
<div>
<p class="paragraph">This is text of box #2</p>
</div>
<div>
<div>
<a href="#" class="doBold">Bold</a>
<a href="#" class="doItalic">Italic</a>
</div>
</div>
</div>
A simplified version of the jQuery:
$(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);
});
try this:
another solution:(that you tried)
one more solve that apply classes only on paragraph: