Alkarin Alkarin - 3 months ago 13
Javascript Question

Toggle specific class element with onclick

Currently I have an unordered list of about 10 of these "container"s.
Each container has a description and a "help-more-content" button.

<div id="item" class="container">

<div class="item">UniqueIdentifierInt</div>

<a href="someLinkUrl">linkName</a>

<div class="trackUri">someLinkUrlString</div>

<div class="description" style="display: none;">DescriptionString</div>

<a class="mt-help-more-content" href="#"></a>

</div>


The functionality is supposed to be when you hit the "help-more-content" button for this container, it will then display that containers description.

However at the moment when the button is clicked, it shows the description for ALL containers on the screen.

Here is the current on click

.on("click", ".mt-help-more-content", function(e) {
$('.description').toggle();
}


Now obviously this toggle function is being called on all "description" elements. How can I specify for it to only act on the current container?

I've checked out other answer here, here, and here but to no real avail.

Is it possible to only toggle the specific class? It doesn't seem you can toggle by an id.

I am new to javascript/html since my background is with Java, so apologies if this is something simple.

Any help is greatly appreciated thank you.

Answer

$.prev will do the trick:

.on("click", ".mt-help-more-content", function(e) {
     $(this).prev('.description').toggle(); 
}
Comments