Repeat jquery action in a class (html)

Asked

Viewed 134 times

0

I saw a toggle show/Hide (click event) function in w3schools and I would like to use it for different classes, but I don’t want to keep repeating the function for each class. In the example below, I want to show/hide content 1 when I click button 1, and show/hide content 2 when I click button 2 without repeating the whole script (so I can add as many classes as I want).

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".teste1").click(function(){
    $(".menor1").toggle();
  });
});
</script>
</head>
<body>

<button class="teste1">Mostrar/ocultar conteúdo do parágrafo 1</button>

<p class="menor1">Este é o conteúdo 1</p>

<button class="teste2">Mostrar/ocultar conteúdo do parágrafo 2</button>

<p class="menor2">Este é o conteúdo 2</p>

</body>
</html>

1 answer

0


In the case of this particular example you can use the method .next, it will only take the next element, for example .next("p") gets the first p after the button. The tip I give you is to understand well how the selectors work, to know how you "get" the elements you want inside the DOM, they are very similar to the CSS selectors and it’s all in the documentation, as in the case of .next()

$(document).ready(function(){
  $("button").click(function(){
    $(this).next("p").toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>


<button class="teste1">Mostrar/ocultar conteúdo do parágrafo 1</button>

<p class="menor1">Este é o conteúdo 1</p>

<button class="teste2">Mostrar/ocultar conteúdo do parágrafo 2</button>

<p class="menor2">Este é o conteúdo 2</p>

Browser other questions tagged

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