jQuery Insert Content


jQuery Insert New Content

jQuery provides several methods, like append()prepend()html()text()before()after()wrap() etc. that allows us to insert new content inside an existing element.

The jQuery html() and text() methods have already covered in the previous chapter, so in this chapter, we will discuss about the rest of them.

jQuery append() Method

The jQuery append() method is used to insert content to the end of the selected elements.

The following example will append some HTML to all the paragraphs on document ready, whereas append some text to the container element on button click.

Example

<script>
$(document).ready(function(){
    // Append all paragraphs
    $("p").append(' <a href="#">read more...</a>');
    
    // Append an element with ID container
    $("button").click(function(){
       $("#container").append("This is demo text.");
    });
});
</script>

Note: The contents or elements inserted using the jQuery append() and prepend() methods is added inside of the selected elements.

jQuery prepend() Method

The prepend() method is used to insert content to the beginning of the selected elements.

The following example will prepend some HTML to all the paragraphs on document ready, whereas prepend some text to the container element on button click.

Example

<script>
$(document).ready(function(){
    // Prepend all paragraphs
    $("p").prepend("<strong>Note:</strong> ");
    
    // Prepend an element with ID container
    $("button").click(function(){
       $("#container").prepend("This is demo text.");
    });
});
</script>

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

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

The jQuery code in the following example will insert a <h1><p> and an <img> element inside the <body> element as a last three child nodes.

Example

<script>
$(document).ready(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="images/smiley.png" alt="Symbol">');
    $("body").append(newHeading, newParagraph, newImage);
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *