In the last article, we have discussed about append method. In this article, we will discuss about JQuery prepend method.

prepend() method is used to insert a content at the beginning of any selected element.

Syntax

$(selector).prepend(content);

In the below example, we have inserted <li> tag in the beginning of <ul> tag.

<!DOCTYPE html>
<html>
<body>
    <ul id="list">
        <li>First LI</li>
        <li>Second LI</li>
    </ul>
    <button type="button" id="add-li">Add to list</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#add-li').click(function() {
                $('#list').prepend('<li>Inserted LI</li>');
            });
        });
    </script>
</body>
</html>

There is also another method prependTo(), which is similar to prepend(). In the prependTo(), you prepend the content in prependTo() element.

Syntax

$(content).prependTo(selector);

Here is the example of prependTo() of above one.

<!DOCTYPE html>
<html>
<body>
    <ul id="list">
        <li>First LI</li>
        <li>Second LI</li>
    </ul>
    <button type="button" id="add-li">Add to list</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#add-li').click(function() {
                $('<li>Inserted LI</li>').prependTo('#list');
            });
        });
    </script>
</body>
</html>

This way, you can use prepend() and prependTo() method to insert content at the beginning of any element. I hope you liked this article.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments