jquery
  1. jquery-prepend

jQuery prepend()

The prepend() method in jQuery is a powerful tool that allows you to insert content at the beginning of an HTML element. It is used to add content before the first child of an element.

Syntax

The syntax for using the prepend() method in jQuery is as follows:

$(selector).prepend(content)
  • selector: This is the HTML element that you want to prepend the content to.
  • content: This is the content that you want to insert at the beginning of the element.

Use

The prepend() method is often used in jQuery to add new content to an HTML element before the first child. This can be useful for adding new content to an existing element without having to manually re-order the elements in the HTML code.

Example

Here is an example of using the prepend() method to add new content to an HTML element:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery prepend() Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#myDiv").prepend("<p>Hello World!</p>");
        });
    </script>
</head>
<body>
    <div id="myDiv">
        <h1>My Heading</h1>
        <p>My content.</p>
    </div>
</body>
</html>
Try Playground

In this example, we use jQuery to add a new paragraph element with the text "Hello World!" to the #myDiv element before the first child, which is the h1 element.

Summary

The prepend() method in jQuery allows you to add new content before the first child of an HTML element. It is a powerful tool that can be used to manipulate the content of a webpage dynamically and without having to modify the HTML code directly. Try using the prepend() method in your jQuery projects to add new content seamlessly.

Published on: