jQuery simplifies adding entirely new elements and content to an existing HTML page.
This allows you to dynamically build websites based on user interaction or data loading.
We will focus on four primary jQuery methods used to add new HTML content:
append() - Inserts content at the end of the selected elements.prepend() - Inserts content at the beginning of the selected elements.after() - Inserts content after the selected elements.before() - Inserts content before the selected elements.The append() method places your new content inside the selected element, at the very end.
If you append to a list (<ul>), it will become the final list item.
$("p").append(" Appended text.");
$("ol").append("The prepend() method places your new content inside the selected element, at the very beginning.
If you prepend to a paragraph, it will appear before the existing text inside that paragraph.
$("p").prepend("Prepended text. ");
The after() method inserts content completely outside and after the selected element.
The before() method inserts content completely outside and before the selected element.
$("img").before("Before image");
$("img").after("After image");
All four methods (append, prepend, before, after) can take an infinite number of new elements as parameters.
You can create these elements using raw HTML, jQuery, or vanilla JavaScript DOM methods.
function appendText() {
var txt1 = "<p>Text.</p>"; // Create element with HTML
var txt2 = $("<p></p>").text("Text."); // Create with jQuery
var txt3 = document.createElement("p"); // Create with DOM
txt3.innerHTML = "Text.";
$("body").append(txt1, txt2, txt3); // Append all 3
}
Which method inserts content INSIDE a selected element, placing it at the very end?
Is it possible to pass multiple strings or elements into the append() method at the same time?