Home > Software engineering >  Change text inside p element with jQuery method chaining
Change text inside p element with jQuery method chaining

Time:11-28

How do I change the text of p element to "Congratulations" when the "Start chaining" button is clicked. I want to add another chaining method to do that.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>jQuery Method Chaining</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      button {
        padding: 10px;
      }
      p {
        width: 200px;
        padding: 30px 0;
        font: bold 24px;
        text-align: center;
        background: #00ced1;
        border: 1px;
        box-sizing: border-box;
      }
    </style>
    <script>
      $(document).ready(function () {
        $('.start').click(function () {
          $('p')
            .animate({ width: '100%' })
            .animate({ fontSize: '35px' })
            .animate({ borderWidth: 30 })
            ;
        });

        $('.reset').click(function () {
          $('p').removeAttr('style');
        });
      });
    </script>
  </head>
  <body>
    <p>Hello !</p>
    <button type="button" >Start Chaining</button>
    <button type="button" >Reset</button>
  </body>
</html>

I tried using .replaceWith() function but it seemed to break other chaining methods


CodePudding user response:

You can use .text("Congratulations") or .html("Congratulations")

Note: Please use proper id so that other p tag doesn't get affected

$(document).ready(function () {
$( "p" )
        $('.start').click(function () {
          let str = "Congratulations"
          $('p')
            .animate({ width: '100%' })
            .animate({ fontSize: '35px' })
            .animate({ borderWidth: 30 })
            .html( str );
        });

        $('.reset').click(function () {
          $('p').removeAttr('style');
        });
      });
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>jQuery Method Chaining</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style>
      button {
        padding: 10px;
      }
      p {
        width: 200px;
        padding: 30px 0;
        font: bold 24px;
        text-align: center;
        background: #00ced1;
        border: 1px;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <p>Hello !</p>
    <button type="button" >Start Chaining</button>
    <button type="button" >Reset</button>
  </body>
</html>

CodePudding user response:

Already figured it out

I used the .text('Congratulations'); as another chain method.

  • Related