jQuery DOM
Learn how to manipulate the Document Object Model with jQuery
🌳 jQuery DOM Manipulation
The DOM (Document Object Model) is the structure of your webpage. jQuery makes it easy to add, remove, and modify elements dynamically, creating interactive web experiences.
// Add new elements to the page
$("body").append("<p>New paragraph added!</p>");
// Remove elements
$(".unwanted").remove();
Result:
New paragraph added!
Unwanted element (removed)
Main DOM Methods
append()
Add content at the end
$("div").append("<p>End</p>")
prepend()
Add content at the beginning
$("div").prepend("<p>Start</p>")
remove()
Remove elements completely
$(".delete").remove()
clone()
Copy elements
$("div").clone().appendTo("body")
🔹 Adding Content
jQuery provides several methods to add new content to your page:
// Add content inside elements
$("#container").append("<p>Added at the end</p>");
$("#container").prepend("<p>Added at the beginning</p>");
// Add content outside elements
$("#container").after("<p>Added after container</p>");
$("#container").before("<p>Added before container</p>");
// Add multiple elements at once
$("ul").append("<li>Item 1</li><li>Item 2</li><li>Item 3</li>");
// Add content from variables
var newContent = "<div class='alert'>Important message!</div>";
$("#messages").append(newContent);
<div id="container">
<p>Original content</p>
</div>
After adding content:
Added before container
Added at the beginning
Original content
Added at the end
Added after container
🔹 Removing Content
Remove elements and content from the DOM:
// Remove elements completely (including event handlers)
$(".unwanted").remove();
// Remove content but keep the element
$("#container").empty();
// Remove elements with specific conditions
$("p:contains('delete')").remove();
$("img[src='old.jpg']").remove();
$("li:gt(4)").remove(); // Remove items after the 5th
// Remove with confirmation
$(".delete-btn").click(function() {
if (confirm("Are you sure you want to delete this?")) {
$(this).closest(".item").remove();
}
});
<div id="container">
<p>Keep this paragraph</p>
<p class="unwanted">Remove this paragraph</p>
<p>Please delete this content</p>
</div>
After removal:
Keep this paragraph
Remove this paragraph (removed)
Please delete this content (removed)
🔹 Replacing Content
Replace existing elements with new content:
// Replace elements with new content
$("p.old").replaceWith("<p class='new'>New paragraph</p>");
// Replace multiple elements
$("img.placeholder").replaceWith(function() {
return "<img src='real-image.jpg' alt='" + $(this).attr("alt") + "'>";
});
// Replace content but keep the element
$("#status").html("<span class='success'>✓ Complete</span>");
// Replace with cloned elements
$(".template").clone().removeClass("template").replaceAll(".placeholder");
<p class="old">Old content</p>
<div id="status">Loading...</div>
🔹 Cloning Elements
Create copies of existing elements:
// Simple clone (without event handlers)
var copy = $("#original").clone();
$("#container").append(copy);
// Clone with event handlers
var copyWithEvents = $("#original").clone(true);
$("#container").append(copyWithEvents);
// Clone and modify
$("#template").clone()
.attr("id", "new-item")
.removeClass("template")
.addClass("active")
.appendTo("#list");
// Clone form fields
$("#add-field").click(function() {
var newField = $(".form-field:first").clone();
newField.find("input").val(""); // Clear the value
newField.insertAfter(".form-field:last");
});
<div id="original" class="card">
<h3>Original Card</h3>
<p>This card will be cloned</p>
</div>
🔹 Wrapping Elements
Wrap elements with new HTML structures:
// Wrap each element individually
$("p").wrap("<div class='paragraph-wrapper'></div>");
// Wrap all elements together
$("p").wrapAll("<div class='content-wrapper'></div>");
// Wrap inner content
$("div").wrapInner("<span class='inner-content'></span>");
// Unwrap elements (remove wrapper)
$("p").unwrap(); // Removes parent wrapper
// Practical example: Add containers to images
$("img").wrap(function() {
return "<div class='image-container' data-src='" + $(this).attr("src") + "'></div>";
});
<p>First paragraph</p>
<p>Second paragraph</p>
After wrapping:
First paragraph
Second paragraph
🔹 Traversing the DOM
Navigate between related elements:
// Parent elements
$("p").parent(); // Direct parent
$("p").parents(); // All ancestors
$("p").parents(".container"); // Specific ancestor
// Child elements
$("div").children(); // Direct children
$("div").children("p"); // Specific children
$("div").find("span"); // All descendants
// Sibling elements
$("h2").next(); // Next sibling
$("h2").prev(); // Previous sibling
$("h2").siblings(); // All siblings
$("h2").siblings("p"); // Specific siblings
// Filtering
$("p").first(); // First element
$("p").last(); // Last element
$("p").eq(2); // Element at index 2
$("p").filter(".highlight"); // Elements with class
<div class="container">
<h2>Title</h2>
<p>First paragraph</p>
<p class="highlight">Second paragraph</p>
<p>Third paragraph</p>
</div>
🔹 Practical Examples
Real-world DOM manipulation examples:
🔸 Dynamic List Management
// Add new list item
$("#add-item").click(function() {
var itemText = $("#new-item").val();
if (itemText.trim() !== "") {
var newItem = "<li>" +
"<span>" + itemText + "</span>" +
"<button class='delete-item'>Delete</button>" +
"</li>";
$("#todo-list").append(newItem);
$("#new-item").val(""); // Clear input
}
});
// Delete list item
$(document).on("click", ".delete-item", function() {
$(this).closest("li").fadeOut(300, function() {
$(this).remove();
});
});
🔸 Image Gallery
// Create image gallery from array
var images = ["img1.jpg", "img2.jpg", "img3.jpg"];
var gallery = $("#gallery");
$.each(images, function(index, src) {
var imgElement = "<div class='gallery-item'>" +
"<img src='" + src + "' alt='Image " + (index + 1) + "'>" +
"<div class='overlay'>" +
"<button class='view-btn'>View</button>" +
"</div>" +
"</div>";
gallery.append(imgElement);
});
🔸 Form Builder
// Add form fields dynamically
$("#add-text-field").click(function() {
var fieldHtml = "<div class='form-group'>" +
"<label>Text Field:</label>" +
"<input type='text' name='field[]' class='form-control'>" +
"<button type='button' class='remove-field'>Remove</button>" +
"</div>";
$("#form-builder").append(fieldHtml);
});
// Remove form fields
$(document).on("click", ".remove-field", function() {
$(this).closest(".form-group").slideUp(300, function() {
$(this).remove();
});
});
🔸 Comments System
// Add new comment
function addComment(author, text) {
var timestamp = new Date().toLocaleString();
var commentHtml = "<div class='comment'>" +
"<div class='comment-header'>" +
"<strong>" + author + "</strong>" +
"<span class='timestamp'>" + timestamp + "</span>" +
"</div>" +
"<div class='comment-body'>" + text + "</div>" +
"<div class='comment-actions'>" +
"<button class='reply-btn'>Reply</button>" +
"<button class='like-btn'>Like</button>" +
"</div>" +
"</div>";
$("#comments").prepend(commentHtml);
}