jQuery & DOM Manipulation

Creating & Inserting Elements

15 min Lesson 14 of 30

Creating & Inserting Elements

jQuery provides powerful methods for dynamically creating new HTML elements and inserting them into your page. This is essential for building interactive web applications that respond to user actions.

Creating New Elements

You can create new HTML elements using the jQuery constructor with an HTML string:

Basic Element Creation: // Create a new paragraph let newPara = $("<p></p>"); // Create with content let heading = $("<h3>New Heading</h3>"); // Create with attributes let link = $("<a>", { text: "Click me", href: "https://example.com", class: "btn btn-primary", target: "_blank" }); // Create complex elements let card = $("<div>", { class: "card", html: "<h4>Card Title</h4><p>Card content</p>" });
Pro Tip: Using the object syntax for attributes is cleaner and safer than concatenating HTML strings, especially when dealing with user input.

Inserting Elements Inside

jQuery offers four methods for inserting content inside existing elements:

.append() - Insert at the End: // Add content at the end of matched elements $("#container").append("<p>Added at the end</p>"); // Multiple elements $("#list").append( $("<li>Item 1</li>"), $("<li>Item 2</li>"), $("<li>Item 3</li>") ); // Using function $("div.box").append(function(index) { return "<span>Box " + (index + 1) + "</span>"; });
.appendTo() - Reverse of append(): // Create and append in one step $("<p>New paragraph</p>").appendTo("#container"); // Move existing element $("#logo").appendTo(".header");
.prepend() - Insert at the Beginning: // Add content at the start of matched elements $("#container").prepend("<p>Added at the start</p>"); // Add timestamp to posts $(".blog-post").prepend(function() { return "<span class='timestamp'>" + new Date().toLocaleDateString() + "</span>"; });
.prependTo() - Reverse of prepend(): // Create and prepend $("<h2>Important Notice</h2>").prependTo(".content"); // Move element to start $(".priority-item").prependTo("#list");

Inserting Elements Outside

These methods insert content before or after elements, as siblings:

.after() - Insert After Element: // Add content after matched elements $("h2").after("<hr>"); // Add edit button after each post $(".post").after("<button class='edit-btn'>Edit</button>"); // Using function $("img").after(function() { return "<p class='caption'>" + $(this).attr("alt") + "</p>"; });
.insertAfter() - Reverse of after(): // Create and insert after $("<div class='ad'>Advertisement</div>").insertAfter(".post:nth-child(3)"); // Move element $("#sidebar").insertAfter(".main-content");
.before() - Insert Before Element: // Add content before matched elements $("h2").before("<div class='spacer'></div>"); // Add icon before links $("a.external").before("<i class='icon-external'></i> ");
.insertBefore() - Reverse of before(): // Create and insert before $("<p class='intro'>Introduction text</p>").insertBefore(".content"); // Move element $(".important-notice").insertBefore("h1");

Practical Example: Dynamic Task List

HTML: <div class="task-manager"> <input type="text" id="taskInput" placeholder="Enter a task"> <button id="addTask">Add Task</button> <button id="addUrgent">Add Urgent Task</button> <ul id="taskList"></ul> <p class="task-count">Total tasks: <span>0</span></p> </div>
jQuery: $(document).ready(function() { // Add task at the end $("#addTask").click(function() { let taskText = $("#taskInput").val().trim(); if (taskText) { let taskItem = $("<li>", { class: "task-item", html: "<span>" + taskText + "</span> <button class='delete-btn'>×</button>" }); $("#taskList").append(taskItem); $("#taskInput").val(""); // Clear input updateTaskCount(); } }); // Add urgent task at the beginning $("#addUrgent").click(function() { let taskText = $("#taskInput").val().trim(); if (taskText) { let urgentTask = $("<li>", { class: "task-item urgent", html: "<span>⚠️ " + taskText + "</span> <button class='delete-btn'>×</button>" }); $("#taskList").prepend(urgentTask); $("#taskInput").val(""); updateTaskCount(); } }); // Delete task (event delegation) $("#taskList").on("click", ".delete-btn", function() { $(this).parent().fadeOut(300, function() { $(this).remove(); updateTaskCount(); }); }); // Update task count function updateTaskCount() { let count = $("#taskList li").length; $(".task-count span").text(count); } // Allow Enter key to add task $("#taskInput").keypress(function(e) { if (e.which === 13) { $("#addTask").click(); } }); });
Performance Tip: When inserting multiple elements, create them all at once or use DocumentFragment to minimize DOM reflows. jQuery automatically optimizes this for you when you pass multiple elements.
Warning: Always sanitize user input before inserting it into the DOM to prevent XSS (Cross-Site Scripting) attacks. Use .text() instead of .html() when dealing with user input, or properly escape HTML entities.

Advanced Techniques

Chaining Multiple Insertions: // Create complex structure with chaining $("#container") .append("<div class='header'></div>") .find(".header") .append("<h1>Title</h1>") .after("<div class='content'></div>") .next() .append("<p>Content paragraph</p>"); // Bulk insert with array let items = ["Apple", "Banana", "Orange"]; let listItems = items.map(function(item) { return $("<li>", { text: item }); }); $("#fruitList").append(listItems);
Conditional Insertion: // Insert based on condition function addNotification(message, type) { let notification = $("<div>", { class: "notification " + type, text: message }); if (type === "error") { notification.prependTo("#notifications"); // Errors at top } else { notification.appendTo("#notifications"); // Others at bottom } // Auto-remove after 5 seconds setTimeout(function() { notification.fadeOut(500, function() { $(this).remove(); }); }, 5000); } // Usage addNotification("Profile updated successfully", "success"); addNotification("Failed to load data", "error");
Exercise: Create a dynamic comment system where users can:
  • Add comments at the bottom of a comment list
  • Add replies to specific comments (inserted after the parent comment)
  • Add a timestamp to each comment
  • Display a "No comments yet" message when the list is empty
  • Delete individual comments with a confirmation

Bonus: Add the ability to edit comments and save them inline.

Best Practices

  • Use object notation when creating elements with attributes for better readability
  • Store references to created elements if you need to manipulate them later
  • Consider performance when inserting many elements - batch operations when possible
  • Validate input before inserting user-generated content
  • Use event delegation for dynamically added elements
  • Clean up event handlers when removing elements to prevent memory leaks

Summary

In this lesson, you learned how to create and insert elements dynamically:

  • Creating elements with $() constructor
  • Inserting inside with .append(), .appendTo(), .prepend(), .prependTo()
  • Inserting outside with .after(), .insertAfter(), .before(), .insertBefore()
  • Building practical dynamic interfaces
  • Performance and security considerations

Next, we'll explore replacing and wrapping elements to transform your DOM structure.

ES
Edrees Salih
22 hours ago

We are still cooking the magic in the way!