SimpleTuts.com

jQuery DOM Manipulation Methods

append() Method

Appends content to selected elements.

$("#container").append("<p>Appended content</p>");

prepend() Method

Prepends content to selected elements.

$("#container").prepend("<p>Prepended content</p>");

after() Method

Inserts content after selected elements.

$("#element").after("<p>Content after</p>");

before() Method

Inserts content before selected elements.

$("#element").before("<p>Content before</p>");

empty() Method

Removes all child nodes of selected elements.

$("#container").empty();

remove() Method

Removes selected elements from the DOM.

$("#element").remove();

All in one Example:


    
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add and Remove contents in HTML using jQuery</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function(){
            $(".btn1").click(function(){
                $(".mypara").append("Hello World");
            });
            $(".btn2").click(function(){
                $(".mypara").prepend("Hello World");
                
            });
            $(".btn3").click(function(){
                $(".mypara").after("Hello World");
             
            });
             $(".btn4").click(function(){
                 $(".mypara").before("Hello World");

             });
             $(".btn5").click(function(){
                 $(".mypara").empty();

             });
             $(".btn6").click(function(){
                 $(".mypara").remove();

             });
        });
    </script>
</head>
<body>
    <p class="mypara"  style="background-color: yellow; padding:15px;">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Possimus molestiae 
        pariatur quod, distinctio itaque modi molestias dignissimos recusandae explicabo 
        accusamus inventore aliquid soluta doloribus quo autem praesentium optio numquam harum.
    </p>
    <br><br>
    <button class="btn1">append</button>
    <button class="btn2">prepend</button>
    <button class="btn3">after</button>
    <button class="btn4">before</button>
    <button class="btn5">empty</button>
    <button class="btn6">remove</button>
</body>
</html>
Run Code