Using jQuery, it is possible to move elements around in the DOM after the page has been loaded. But that requires writing Javascript code, and sometimes it can be useful to declare what to move and where to move it, rather than writing procedural code to execute the move. For example, static content in a CMS webpage module can include a declarative placeholder element which indicates where to insert dynamically-generated content.

The a4dn.replacewith.js plugin can be found in Accelerator MVC's DistributableContent project. In generated MVC projects, you'll find the plugin in the Scripts/ folder of your project. When this plugin is loaded, it extends jQuery with a function named $.a4dn_process_replacewith().

This function is used to process elements that have data-replacewith attributes. It takes the value of the attribute as a jQuery selector or an element id, finds the matching element within the page, and moves it to the location of the element that has the data-replacewith attribute.

This is typically used for CMS static web content pages that have dynamically-inserted content, to indicate where the dynamic content should be located within the static content.

The flag data-replacewith-mode="inner" can be used when you only want to move the children of the specified element, instead of the entire element. This is for situations where the markup structure won't allow an extra wrapper element to be inserted.

Either way, after the function is run the div with data-replacewith will be gone from the DOM, and if inner mode is used the container element will also be gone from the DOM.

Usage - Markup:

<div data-replacewith="#dynamic">Placeholder content; this entire div will be replaced with #dynamic.</div>

<div data-replacewith="#dynamic" data-replacewith-mode="inner">This div will be replaced with #dynamic's children.</div>

Usage - Process all attributes at page ready:

$(function() {
    $.a4dn_process_replacewith();
});

With no argument, a4dn_process_replacewith() searches the entire page.

Usage - Process specific container after page load (eg: when inserting content from an ajax request):

onSuccess: function (data) {
    $("#container").html($(data.markup));
    $.a4dn_process_replacewith("#container");
}

The #container argument restricts the search to just the newly added elements.