jQuery & DOM Manipulation

Replacing & Wrapping Elements

12 min Lesson 15 of 30

Replacing & Wrapping Elements

jQuery provides powerful methods to replace existing elements with new content or wrap elements with additional HTML structure. These techniques are essential for transforming your DOM dynamically.

Replacing Elements

The .replaceWith() method replaces matched elements with new content:

.replaceWith() - Replace Element: // Replace with HTML string $(".old-button").replaceWith("<button class='new-button'>Updated Button</button>"); // Replace with jQuery object let newElement = $("<div>", { class: "new-content", text: "This is new content" }); $(".old-content").replaceWith(newElement); // Replace using function $("p.status").replaceWith(function() { let status = $(this).text(); return "<span class='badge'>" + status + "</span>"; }); // Replace multiple elements $("img.placeholder").replaceWith(function() { return "<div class='image-loaded'><img src='" + $(this).data("src") + "'></div>"; });
.replaceAll() - Reverse of replaceWith(): // Create new element and replace all matches $("<h2>New Heading</h2>").replaceAll("h3.old-heading"); // Replace all error messages $("<div class='alert alert-success'>Success!</div>").replaceAll(".error-message");
Important: When you replace an element, all event handlers and data associated with the old element are removed. If you need to preserve them, consider hiding the old element and showing a new one instead.

Practical Example: Dynamic Status Badge

HTML: <div class="order-list"> <div class="order-item"> <span class="order-number">#1234</span> <span class="status" data-status="pending">Pending</span> </div> <div class="order-item"> <span class="order-number">#1235</span> <span class="status" data-status="shipped">Shipped</span> </div> </div>
jQuery: $(document).ready(function() { // Replace status text with styled badges $(".status").replaceWith(function() { let status = $(this).data("status"); let statusText = $(this).text(); let badgeClass = ""; switch(status) { case "pending": badgeClass = "badge-warning"; break; case "shipped": badgeClass = "badge-info"; break; case "delivered": badgeClass = "badge-success"; break; case "cancelled": badgeClass = "badge-danger"; break; } return $("<span>", { class: "badge " + badgeClass, text: statusText, "data-status": status }); }); });

Wrapping Elements

Wrapping methods allow you to surround elements with new HTML structure:

.wrap() - Wrap Each Element: // Wrap each paragraph in a div $("p").wrap("<div class='paragraph-wrapper'></div>"); // Wrap with jQuery object $("img").wrap($("<div>", { class: "image-container" })); // Wrap using function (different wrapper for each element) $(".card").wrap(function(index) { return "<div class='card-wrapper card-" + index + "'></div>"; }); // Wrap form inputs with labels $("input[type='text']").wrap(function() { let placeholder = $(this).attr("placeholder"); return "<div class='form-group' data-label='" + placeholder + "'></div>"; });
.wrapAll() - Wrap All Elements Together: // Wrap all paragraphs in a single container $("p").wrapAll("<div class='content-wrapper'></div>"); // Wrap selected items in a group $(".product.selected").wrapAll("<div class='selected-products'></div>"); // Create a gallery from images $(".gallery img").wrapAll("<div class='image-gallery'><div class='gallery-inner'></div></div>");
Note: .wrapAll() moves all matched elements to a single location and wraps them together. If elements are scattered across the DOM, they will be moved to where the first element was located.
.wrapInner() - Wrap Content Inside Elements: // Wrap the content of each paragraph $("p").wrapInner("<span class='text-content'></span>"); // Add icon wrapper inside buttons $("button").wrapInner("<span class='btn-text'></span>"); // Wrap list item content $("li").wrapInner(function() { return "<div class='list-content'></div>"; }); // Add link wrapper around heading text $("h2").wrapInner("<a href='#'></a>");
.unwrap() - Remove Parent Wrapper: // Remove parent wrapper $("span").unwrap(); // Remove specific parent $(".wrapped-content").unwrap(".wrapper"); // Unwrap multiple levels $(".nested-content").unwrap().unwrap(); // Remove two parent levels

Practical Example: Image Gallery with Lightbox

HTML: <div class="photo-gallery"> <img src="photo1.jpg" alt="Photo 1"> <img src="photo2.jpg" alt="Photo 2"> <img src="photo3.jpg" alt="Photo 3"> </div>
jQuery: $(document).ready(function() { // Wrap each image in a figure with caption $(".photo-gallery img").wrap(function() { let alt = $(this).attr("alt"); return "<figure class='gallery-item'></figure>"; }).after(function() { return "<figcaption>" + $(this).attr("alt") + "</figcaption>"; }); // Wrap all gallery items in a container $(".gallery-item").wrapAll("<div class='gallery-grid'></div>"); // Add lightbox functionality $(".gallery-item img").click(function() { let imgSrc = $(this).attr("src"); let imgAlt = $(this).attr("alt"); // Create lightbox overlay let lightbox = $("<div>", { class: "lightbox-overlay", html: "<div class='lightbox-content'>" + "<img src='" + imgSrc + "' alt='" + imgAlt + "'>" + "<button class='close-lightbox'>×</button>" + "</div>" }); $("body").append(lightbox); lightbox.fadeIn(300); }); // Close lightbox $(document).on("click", ".close-lightbox, .lightbox-overlay", function(e) { if (e.target === this) { $(".lightbox-overlay").fadeOut(300, function() { $(this).remove(); }); } }); });

Advanced Wrapping Techniques

Complex Wrapping Structures: // Wrap with multiple nested elements $(".quote").wrap( "<div class='quote-container'>" + "<div class='quote-inner'>" + "</div>" + "</div>" ); // Wrap and add sibling elements $("blockquote").wrap("<div class='quote-wrapper'></div>") .parent() .prepend("<span class='quote-icon'>"</span>") .append("<span class='quote-icon'>"</span>"); // Conditional wrapping $("img").each(function() { if ($(this).width() > 500) { $(this).wrap("<div class='large-image-wrapper'></div>"); } else { $(this).wrap("<div class='small-image-wrapper'></div>"); } });

Combining Replace and Wrap

Transform Elements: // Replace and wrap in one operation function upgradeButton(selector) { $(selector).each(function() { let buttonText = $(this).text(); let buttonClass = $(this).attr("class"); // Create new button structure let newButton = $("<button>", { class: buttonClass + " upgraded", html: "<span class='btn-icon'></span>" + "<span class='btn-text'>" + buttonText + "</span>" }); // Replace old button $(this).replaceWith(newButton); }); } // Usage upgradeButton(".old-style-btn"); // Replace text nodes with formatted elements $("p").contents().filter(function() { return this.nodeType === 3; // Text node }).wrap("<span class='text-node'></span>");
Exercise: Create a dynamic pricing table enhancer that:
  • Wraps each price in a styled container
  • Replaces currency symbols with icon fonts
  • Wraps feature lists in expandable sections
  • Adds a "Popular" ribbon to the middle pricing tier
  • Wraps action buttons in a button group

Bonus: Add hover effects that temporarily replace button text with "Choose Plan".

Best Practices

  • Performance: Wrapping and replacing are expensive operations; batch them when possible
  • Event handlers: Remember that .replaceWith() removes event handlers from the old element
  • Data preservation: Use .data() to preserve information before replacing
  • Semantic HTML: Ensure wrapped structures maintain proper HTML semantics
  • Unwrap carefully: Make sure parent elements exist before calling .unwrap()
  • Test thoroughly: Wrapping can affect CSS selectors and layout

Performance Considerations

Efficient Wrapping: // Inefficient: Multiple DOM operations $("li").each(function() { $(this).wrap("<div class='item-wrapper'></div>"); }); // Better: Single operation for all elements $("li").wrap("<div class='item-wrapper'></div>"); // Cache jQuery objects let items = $(".item"); let wrapper = $("<div class='wrapper'></div>"); items.wrapAll(wrapper);

Summary

In this lesson, you learned how to replace and wrap elements:

  • Replacing elements with .replaceWith() and .replaceAll()
  • Wrapping each element with .wrap()
  • Wrapping multiple elements together with .wrapAll()
  • Wrapping element content with .wrapInner()
  • Removing wrappers with .unwrap()
  • Practical applications for UI enhancement
  • Performance and best practices

Next, we'll explore removing elements from the DOM safely and efficiently.

ES
Edrees Salih
23 hours ago

We are still cooking the magic in the way!