How to toggle text inside and element on click using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery text() method

You can use the jQuery click() method in combination with the text() method to replace or toggle the text inside an element such as a link (i.e. an anchor <a>), <div> or <button> element dynamically using the jQuery.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Toggle Text inside Elements</title>
  • <style type="text/css">
  •     button {
  •         padding: 5px 10px;
  •         font-size: 14px;
  •     }
  • </style>
  • <script src=""></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $("button").click(function(){
  •             $(this).text($(this).text() == 'Order by Alphabet' ? 'Order by Category' : 'Order by Alphabet');
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button type="button">Order by Alphabet</button>
  • <p><strong>Note:</strong> Click on the button to swap the text.</p>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.