How to change div text with jQuery toggle?

Sometimes, we want to change div text with jQuery toggle.

In this article, we’ll look at how to change div text with jQuery toggle.

How to change div text with jQuery toggle?

To change div text with jQuery toggle, we can call the text method of an element.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div id="box">
  <div class="open">Show</div>
  <div class="showpanel">This is content</div>

  <div class="open2">Show</div>
  <div class="showpanel2">This is content</div>
</div>

to add some HTML elements.

Then we write:

$('.open').click(function() {
  const link = $(this);
  $('.showpanel').slideToggle('slow', function() {
    if ($(this).is(':visible')) {
      link.text('close');
    } else {
      link.text('open');
    }
  });
});

We select the divs with class open with $('.open').

Then we call click to add click handlers to them.

Next, we select the divs with class showpanel with $('.showpanel').

And then we call slidetoggle to add a slide toggle effect when we they’re shown or hidden from the screen.

In the event handler which is called when the animation is done, we call link.text to change the text of the link we selected earlier.

Conclusion

To change div text with jQuery toggle, we can call the text method of an element.