jQuery Insert

jQuery makes it possible to insert new content inside an existing element by providing several methods such as append(), prepend(), html(), text(), before(), after(), wrap() and so on.

However the jQuery html() and text() methods have already been covered in the previous tutorials, so in this tutorial, we will discuss the other ones mentioned above.

 

jQuery append() Method

The jQuery append() method is typically used for inserting content to the end of a selected element.

The example below shows how you can append some HTML to all the paragraphs on document ready, and append some text to the container element on button click.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting HTML Contents At the End of the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Append all paragraphs on document ready
    $("p").append(' <a href="#">read more...</a>');
    
    // Append a div container on button click
    $("button").click(function(){
       $("#container").append("This is demo text.");
    });
});
</script>
</head>
<body>
    <button type="button">Insert Text</button>
    <div id="container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.</p>
        <p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti.</p>
    </div>
</body>
</html>

 

jQuery prepend() Method

For you to insert content at the beginning of the selected elements by using the prepend() method.

The example below shows how you can prepend some HTML to all the paragraphs on document ready, and prepend some text to the container element on button click.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting HTML Contents At the Start of the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Prepend all paragraphs on document ready
    $("p").prepend("<strong>Note:</strong> ");
    
    // Prepend a div container on button click
    $("button").click(function(){
       $("#container").prepend("This is demo text.");
    });
});
</script>
</head>
<body>
    <button type="button">Insert Text</button>
    <div id="container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.</p>
        <p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti.</p>
    </div>
</body>
</html>

 

Insert Multiple Elements with append() & prepend() Method

The append() and prepend() in jQuery also support passing in multiple arguments as input.

Take a look at the jQuery code in example below as it shows how to insert a <h1>, <p> and an <img> element inside the <body> element as a last three child nodes.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Append or Prepend Multiple Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var newHeading = "<h1>Important Note:</h1>";
        var newParagraph = document.createElement("p");
		newParagraph.innerHTML = "<em>Lorem Ipsum is dummy text...</em>";
        var newImage = $('<img src="/examples/images/smiley.png" alt="Symbol">');
        $("body").append(newHeading, newParagraph, newImage);
    });
});
</script>
</head>
<body>
    <button type="button">Insert Contents</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante, metus ac nisl bibendum.</p>
</body>
</html>

 

jQuery before() Method

To insert content before the selected elements the before() method in jQuery can be used.

The example below shows how you can insert a paragraph before the container element on document ready, and insert an image before the <h1> element on button click.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting HTML Contents Before or After the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Add content after a div container on document ready
    $("#container").after("<p>&mdash; The End &mdash;</p>");
    
    // Add content before a div container on document ready
    $("#container").before("<p>&mdash; Demo Text &mdash;</p>");
    
    // Add content after heading on button click
    $("button.insert-after").click(function(){
        $("h1").after('<img src="/examples/images/marker-right.gif" alt="Symbol">');
    });
    
    // Add content before heading on button click
    $("button.insert-before").click(function(){
        $("h1").before('<img src="/examples/images/marker-left.gif" alt="Symbol">');
    });
});
</script>
<style>
    h1{
        display: inline-block; /* To place marker image and heading in one line */
    }
    body{
        text-align: center;
    }
</style>
</head>
<body>
    <h1>Hello World</h1>
    <hr>
    <button type="button" class="insert-before">Insert Before</button>
    <button type="button" class="insert-after">Insert After</button>
    <hr>
    <div id="container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus ligula.</p>
        <p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti. Aliquam sit amet gravida nibh, facilisis gravida odio. Phasellus auctor velit at lacus blandit, commodo iaculis justo viverra. Etiam vitae est arcu. Mauris vel congue dolor. Aliquam eget mi mi. Fusce quam tortor, commodo ac dui quis, bibendum viverra erat. Maecenas mattis lectus enim, quis tincidunt dui molestie euismod. Curabitur et diam tristique, accumsan nunc eu, hendrerit tellus.</p>
    </div>
</body>
</html>                                		

 

jQuery after() Method

The after() method in jQuery is typically used to insert content after the selected elements.

The example below shows how you can insert a paragraph after the container element on document ready, and insert an image after the <h1> element on button click.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting HTML Contents Before or After the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Add content after a div container on document ready
    $("#container").after("<p>&mdash; The End &mdash;</p>");
    
    // Add content before a div container on document ready
    $("#container").before("<p>&mdash; Demo Text &mdash;</p>");
    
    // Add content after heading on button click
    $("button.insert-after").click(function(){
        $("h1").after('<img src="/examples/images/marker-right.gif" alt="Symbol">');
    });
    
    // Add content before heading on button click
    $("button.insert-before").click(function(){
        $("h1").before('<img src="/examples/images/marker-left.gif" alt="Symbol">');
    });
});
</script>
<style>
    h1{
        display: inline-block; /* To place marker image and heading in one line */
    }
    body{
        text-align: center;
    }
</style>
</head>
<body>
    <h1>Hello World</h1>
    <hr>
    <button type="button" class="insert-before">Insert Before</button>
    <button type="button" class="insert-after">Insert After</button>
    <hr>
    <div id="container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus ligula.</p>
        <p>Quis quam ut magna consequat faucibus. Pellentesque eget nisi a mi suscipit tincidunt. Ut tempus dictum risus. Pellentesque viverra sagittis quam at mattis. Suspendisse potenti. Aliquam sit amet gravida nibh, facilisis gravida odio. Phasellus auctor velit at lacus blandit, commodo iaculis justo viverra. Etiam vitae est arcu. Mauris vel congue dolor. Aliquam eget mi mi. Fusce quam tortor, commodo ac dui quis, bibendum viverra erat. Maecenas mattis lectus enim, quis tincidunt dui molestie euismod. Curabitur et diam tristique, accumsan nunc eu, hendrerit tellus.</p>
    </div>
</body>
</html>                                		

 

Insert Multiple Elements with before() & after() Method

In jQuery the before() and after() methods do supports passing in multiple arguments as input. 

The example below shows how you can insert a <h1>, <p> and an <img> element before the <p> elements.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inserting Multiple Elements Before or After the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var newHeading = "<h2>Important Note:</h2>";
        var newParagraph = document.createElement("p");
        newParagraph.innerHTML = "<em>Lorem Ipsum is dummy text...</em>";
        var newImage = $('<img src="/examples/images/smiley.png" alt="Symbol">');
        $("p").before(newHeading, newParagraph, newImage);
    });
    
});
</script>
</head>
<body>
    <button type="button">Insert Contents</button>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante, metus ac nisl bibendum.</p>
</body>
</html>

 

jQuery wrap() Method

The wrap() method in jQuery is used to wrap an HTML structure around the selected elements.

The jQuery code in the example below shows how you can wrap the container elements with an <div> element with the class ‘.wrapper’ on document ready, and wrap all the inner content of the paragraph elements first with the <b> and then with <em> element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Wrapping HTML Around the Elements in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Wrap div container with another div on document ready
    $(".container").wrap('<div class="wrapper"></div>');
    
    // Wrap paragraph's content on button click
    $("button").click(function(){
        $("p").contents().wrap("<em><b></b></em>");
    });
});
</script>
<style>
    .wrapper{
        padding: 20px;
        background: #f0e68c;
        margin: 10px 0;
    }
    .container{
        padding: 15px;
        background: #fff;
        font-size: 24px;
    }
</style>
</head>
<body>
    <button type="button">Wrap Demo Text</button>
    <div class="container">
        <p>This is demo text.</p>
    </div>
</body>
</html>