jQuery add content at the beginning of selected element using prepend

  390 views   11 months ago jQuery

In the previous 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]