DOM Elements API

$.replace()

async

Replaces DOM elements with other DOM elements.

  • Accepts a DOM element or a collection of elements (array, NodeList, or HTMLCollection) to be replaced as the first argument.
    Accepts a DOM element or a collection of elements (array, NodeList, or HTMLCollection) to replace with as the second argument.
    Accepts an optional third argument as a boolean value (true or false):
    Argument
    Description
    true
    Moves the DOM elements for replacement without duplicating them.
    false
    Duplicates the DOM elements for replacement, leaving the original in place.
    This is the default value.
  • Returns the replaced DOM element if the first and second arguments are DOM elements.
    Returns an array of DOM elements that were replaced if the first argument is a DOM element and the second argument is a collection of elements (array, NodeList, or HTMLCollection).
    Returns an array of arrays of DOM elements that were replaced if the first and second arguments are collections of elements (array, NodeList, or HTMLCollection).
    Returns false if the DOM element cannot be replaced.
  • It is not necessary to wait for the method to be executed using await if not needed.
Example:
await $.replace($('div'), $('span'));
// Replaces the <div> element with a <span> element.
// <span>

await $.replace($('div ?'), $('span'));
// Replaces all <div> elements with a <span> element.
// [<span>, <span>, <span>]

await $.replace($('div'), [$('span'), $('nav')], true);
// Replaces the <div> element with <span> and <nav> elements, then removes those <span> and <nav> elements.
// [<span>, <nav>]

await $.replace($('div ?'), [$('span'), $('nav')], true);
// Replaces all <div> elements with <span> and <nav> elements, then removes those <span> and <nav> elements.
// [[<span>, <nav>], [<span>, <nav>], [<span>, <nav>]]