Create a paragraph element with some text and append it to end of document body using jQuery


In this article, the task is to create a paragraph element with some text and append it to end of document body using jQuery.

Using jQuery, it is easy to add new elements/content in a particular position inside an HTML document. We have four methods that are used to add new content:

  • append() − This method adds the content at the end of selected elements.

  • prepend() − This method adds the content at the beginning of selected elements.

  • after() − This method adds the content after the selected elements.

  • before() − This method adds the content before the selected elements.

Here, the task is to add a paragraph element with some text at the end of the document body. So, we use the append() method.

Syntax

Following is the syntax of the jQuery append() method −

$(selector).append("content");

The "content" is a required parameter. It specifies the content to add (can also contain HTML tags).

Example

In the following example, we are creating a paragraph element with some text and appending it to the end of the document body using jQuery append() method −

<!DOCTYPE html>
<head>
   <title>Append Text Example</title>
   <!-- Import jQuery cdn library -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
      $(document).ready(function () {
         $("button").click(function () {
            $("body").append("<p>The text is appended.</p>");
         });
      });
   </script>
</head>
<body style="text-align: center;">
   <h1 style="color: seagreen;">Welcome to Tutorialspoint</h1>
   <p>Click the button below to append text at the end of this document.</p>
   <button>Click Here!</button>
</body>
</html>

After executing the above program, click on the button to append the text at the end of the document body.

Updated on: 09-Feb-2024
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements