Skip to content

Commit 170c2ae

Browse files
committed
Allow CSS selector as target
1 parent be6b73a commit 170c2ae

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

src/Portal.svelte

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,34 @@
11
<script>
2-
import { onMount, onDestroy } from "svelte";
2+
import { onMount } from "svelte";
33
44
export let target = document.body;
55
6+
let targetEl;
67
let portal;
78
let componentInstance;
89
910
onMount(() => {
11+
if (typeof target === "string") {
12+
targetEl = document.querySelector(target);
13+
// Force exit
14+
if (targetEl === null) {
15+
return () => {};
16+
}
17+
} else if (target instanceof HTMLElement) {
18+
targetEl = target;
19+
} else {
20+
throw new TypeError(
21+
`Unknown target type: ${typeof target}. Allowed types: String (CSS selector), HTMLElement.`
22+
);
23+
}
24+
1025
portal = document.createElement("div");
11-
target.appendChild(portal);
26+
targetEl.appendChild(portal);
1227
portal.appendChild(componentInstance);
13-
});
1428
15-
onDestroy(() => {
16-
target.removeChild(portal);
29+
return () => {
30+
targetEl.removeChild(portal);
31+
};
1732
});
1833
</script>
1934

0 commit comments

Comments
 (0)