How to change the class of one element by clicking on another using Jquery

Asked

Viewed 52 times

1

I am building a comment system and I would like a reply form to appear when I click on a button. The problem is that there is a response form for each comment, and I would like it only to appear the element response form that I clicked on. Follows the base of the code, being "answer" the class of the button to call the form "formularyRespose".

$(document).ready(function(){
    $(".resposta").click(function(event){
        event.preventDefault();
        $(.formularioResposta).addClass('selecionado');
        $(".selecionado").show(3000);
    });
});

1 answer

0


You can use the closest, siblings, parent (what determines their use is the hierarchy of the elements, that is how the HTML is, what is not in your question), for example:

$(".resposta").click(function(event){
    event.preventDefault();
    $(this).siblings('.formularioResposta').addClass('selecionado');
    $(".selecionado").show(3000);
});

Demonstration:

$('.formularioResposta').hide();

$(".resposta").click(function(event) {
  event.preventDefault();

  campoComentario = $(this).siblings('.formularioResposta');

  if (campoComentario.is('.selecionado')) {
    campoComentario.removeClass('selecionado').hide(300);
  } else {
    campoComentario.addClass('selecionado').show(300);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>
<div>
  <div class="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>
<div>
  <div class="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.