jQuery - append content inside selected element

JQuery has made easy to handle Javascript events and animation. In this article we will see how to inserts content at the end of selected elements. We will use jQuery.append() method to insert content into element.

Syntax

$(selector).append(content);

In the below example, we have inserted <li> tag inside <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').append('<li>Next LI</li>');
            });
        });
    </script>
</body>
</html>

There is another method appendTo(), which is similar to append(). In this method, you append the content in appendTo() element.

Syntax

$(content).appendTo(selector);

Here is the above example of appendTo().

<!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>Next LI</li>').appendTo('#list');
            });
        });
    </script>
</body>
</html>

In the new article we will use prepend() and prependTo() methods. Thank you for support!

Tags: