We will learn how to insert new elements or contents to the document using jQuery.
jQuery provides several methods that allows us to insert or add new content inside an existing elemen.
The jQuery append() method inserts content AT THE END of the selected HTML elements.
The jQuery prepend() method inserts content to the beginning of the selected HTML elements.
In both examples above, we have only inserted some text/HTML at the beginning/end of the selected HTML elements.
However, both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the examples above), with jQuery, or with JavaScript code and DOM elements.
In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append() method (this would have worked for prepend() too) :
The jQuery after() method inserts content after the selected HTML elements. And before() method inserts content BEFORE the selected HTML elements.
The jQuery before() and after() also supports passing in multiple arguments as input. The following example will insert a <h1>, <p> and an <img> element before the <p> elements.
<script>
$(document).ready(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="images/smiley.png" alt="Symbol">');
$("p").before(newHeading, newParagraph, newImage);
});
</script>
We will learn about remove in next chapter Click