Trongate Website Homepage

Swap Operations

The mx-swap attribute in Trongate MX controls how the response content is inserted into the target element. This attribute provides a range of options for updating the DOM, allowing developers to fine-tune how and where content is placed, based on their application's needs.

The mx-swap Attribute

The mx-swap attribute determines the method used to insert or replace content in the target element specified by the mx-target attribute. If the mx-swap attribute is not provided, it defaults to innerHTML, which replaces the inner HTML of the target element.

Available Swap Methods:

Method Description Example Syntax
innerHTML (default) Replaces the inner HTML of the target element with the response content. mx-swap="innerHTML"
outerHTML Replaces the entire target element with the response content. mx-swap="outerHTML"
textContent Replaces the text content of the target element with the response content. mx-swap="textContent"
beforebegin Inserts the response content before the target element. mx-swap="beforebegin"
afterbegin Inserts the response content as the first child of the target element. mx-swap="afterbegin"
beforeend Inserts the response content as the last child of the target element. mx-swap="beforeend"
afterend Inserts the response content after the target element. mx-swap="afterend"
delete Removes the target element from the DOM. mx-swap="delete"
none Does not insert any content into the DOM. Useful for out-of-band swaps where no direct DOM update is needed. mx-swap="none"

Examples:

Prepend Data:

This example uses the mx-swap="afterbegin" method to insert the response content as the first child of the target element.

<button mx-get="api/data" mx-target="#result" mx-swap="afterbegin">Prepend Data</button>
<div id="result"></div>

Replace Entire Element:

Here, mx-swap="outerHTML" is used to replace the entire target element with the response content.

<button mx-get="api/data" mx-target="#result" mx-swap="outerHTML">Replace Element</button>
<div id="result">Old Content</div>

Insert Before Target:

This example demonstrates how to insert content before the target element using mx-swap="beforebegin".

<button mx-get="api/data" mx-target="#result" mx-swap="beforebegin">Insert Before</button>
<div id="result">Content Here</div>

Remove Target Element:

Using mx-swap="delete" removes the target element from the DOM entirely.

<button mx-get="api/data" mx-target="#result" mx-swap="delete">Remove Element</button>
<div id="result">This will be deleted</div>

Summary

The mx-swap attribute in Trongate MX enhances the flexibility of dynamic content updates by providing various methods for inserting or replacing content within the target element. Understanding and leveraging these methods allows developers to create sophisticated and responsive web applications, making the most of Trongate MX's capabilities.