×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery prepend() Method

jQuery | prepend() Method: Learn about the jQuery prepend() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 14, 2022

prepend() Method

When we need to add some content or text to an HTML document, there are various methods for it using jQuery. One of them is - prepend() method. This method is a lot similar to the before() in jQuery. This method is used to add the content at the beginning of the selected element. The content that has to be added can be specified over here.

prepend() Method Syntax

$('selector').prepend('content',function());

The element is selected using the selector. This method takes two parameters – content, and function. The content is the text or data that you wish to provide over there. The function is an optional parameter. When the content is specified within the prepend() method, then it can have any HTML tag, CSS properties, jQuery objects, and DOM elements in it.

Hence, this method is useful to add any type of content to prepend the targeted location. It will add the specified content and prepend all the matched elements with the selector. The below-provided example will help to understand the implementation of the prepend() method more easily. The content gets added as many times as the button is clicked.

jQuery prepend() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <h2>jQuery - Prepend</h2>
    <p>Click the button to implement the prepend() method in jQuery.</p>
    <button>Prepend</button>
    <hr>
    <div>Monday</div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            $("div").prepend("<b>Day One: </b>");
        });
    });
  </script>
</html>

Output:

Example 1: jQuery prepend() Method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.