-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace.js
More file actions
55 lines (50 loc) · 1.65 KB
/
replace.js
File metadata and controls
55 lines (50 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import $, {Dabby} from "../../core/dabby/dabby.js";
import getVal from "../../internal/getval/getval.js";
import "../../core/get/get.js";
import "../../manipulation/clone/clone.js";
const factory = (obj, html, all) => {
let source = (all ? $(html) : obj).get(),
target = (all ? obj : $(html)).get(),
isFunc = typeof target === "function",
i = source.length;
if (!isFunc) {
target = $(target);
}
while (i--) {
let n = target.length,
parent = source[i].parentNode;
while (n--) {
const replace = isFunc ? getVal(target[n], n, target[n]) : target[n];
if (n) {
source[i].insertAdjacentElement("beforebegin", $(replace).clone(true).get(0));
} else {
source[i] = parent.replaceChild(i ? $(replace).clone(true).get(0) : replace, source[i]);
}
}
}
return $(source);
};
/**
* Removes some or all of the items in the collection from the DOM
*
* @memberof Dabby#
* @function replaceWith
* @param {(string|Node|Node[]|Dabby|function)} html An HTML string, Node, array of Nodes or function that returns HTML
* @returns {Dabby} The original Dabby collection
*/
const replaceWith = function (html) {
return factory(this, html, false);
}
Object.defineProperty(Dabby.prototype, "replaceWith", {value: replaceWith});
/**
* Removes some or all of the items in the collection from the DOM
*
* @memberof Dabby#
* @function replaceAll
* @param {selector} html A selector, HTML string, Node, array of Nodes, Dabby collection or a callback function
* @returns {Dabby} The original Dabby collection
*/
const replaceAll = function (html) {
return factory(this, html, true);
}
Object.defineProperty(Dabby.prototype, "replaceAll", {value: replaceAll});