LewisJWright LewisJWright - 5 months ago 8
HTML Question

how to only show specific element when another is clicked

I have a set of tabs that will each contain there own set of questions with each question having a specific answer.

The tab structure is sound and exactly how I wanted it to be when built. My problem lies with the questions and answers themselves.

The desired functionality is when a question is clicked the answer for that question should be shown. I have a simple grasp of it here with this JSFiddle but I am struggling on how to differentiate between what question is being clicked and therefore which answer to show.

Basic understanding of whats needed:

$('.question-text').click(function(){
$(".answer-text").toggleClass("hidden");
});


I saw this fiddle that uses jquery's
closest
but cant figure out how to convert that to my particular code. Here is what I have tried with no avail:

$(".question").each(function(){
$('.question-text').click(function(){
var $par=$(this).closest('.answer')
$par.find(".answer-text").slideDown("1000");
});
})


Any help on this would be greatly appreciated!

Answer

You can remove iterating question.each and simply bind click on all the question-text.

When the question-text is clicked , grab the next sibling which is your answer.

$('.question-text').click(function(){
         var $par=$(this).next()
         $par.find(".answer-text").toggleClass("hidden");
     });
})