Marc Hoover Marc Hoover - 2 months ago 7
jQuery Question

Toggling text with jQuery without toggling all other text

Ok, so obviously I am not good at jQuery, but I know enough to know how it works. So what I need is a simple toggle, but since the text is generated by php, i need it to only toggle the text underneath that link, example:

<a href="#">Toggle</a>
<p class="mydesc">This text needs to be hidden until the toggle is activated.</p>
<a href="#">Toggle</a>
<p class="mydesc">This text needs to be hidden until the toggle is activated2.</p>


...And i will have about 20 more just like this. I know I can change .mydesc to a unique #id, but then I would have a ton of jQuery code to have toggle on each individual #id. What is the simplest way to do this?

Answer

Add a class, and just target the next element

<a href="#" class="myAnchor">Toggle</a>

then

$('.myAnchor').on('click', function() {
    $(this).next('p').toggle();
});

FIDDLE