Skip to content

Commit 92fb400

Browse files
committed
core dom: Add create_from_string to create a DOM Element from a string.
1 parent 84cfeba commit 92fb400

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
- core dom: Add ``find_parents`` to find all parents of an element matching a CSS selector.
4949
- core dom: Add ``find_scoped`` to search for elements matching the given selector within the current scope of the given element
5050
- core dom: Add ``is_visible`` to check if an element is visible or not.
51+
- core dom: Add ``create_from_string`` to create a DOM Element from a string.
5152
unless an ``id`` selector is given - in that case the search is done globally.
5253
- pat date picker: Support updating a date if it is before another dependent date.
5354
- pat tabs: Refactor based on ``ResizeObserver`` and fix problems calculating the with with transitions.

src/core/dom.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,13 @@ const is_visible = (el) => {
8080
return el.offsetWidth > 0 && el.offsetHeight > 0;
8181
};
8282

83+
const create_from_string = (string) => {
84+
// Create a DOM element from a string.
85+
const div = document.createElement("div");
86+
div.innerHTML = string.trim();
87+
return div.firstChild;
88+
};
89+
8390
const dom = {
8491
toNodeArray: toNodeArray,
8592
querySelectorAllAndMe: querySelectorAllAndMe,
@@ -89,6 +96,7 @@ const dom = {
8996
find_parents: find_parents,
9097
find_scoped: find_scoped,
9198
is_visible: is_visible,
99+
create_from_string: create_from_string,
92100
};
93101

94102
export default dom;

src/core/dom.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,33 @@ describe("core.dom tests", () => {
249249
done();
250250
});
251251
});
252+
253+
describe("create_from_string", () => {
254+
it("Creates a DOM element from a string", (done) => {
255+
let res = dom.create_from_string(`
256+
<section id="section1">
257+
<span class='yo'>does work.</span>
258+
</section>`);
259+
260+
expect(res.getAttribute("id")).toEqual("section1");
261+
expect(res.querySelector("span.yo").textContent).toEqual(
262+
"does work."
263+
);
264+
265+
res = dom.create_from_string(`
266+
<section id="section1"></section>
267+
<section id="section2"></section>
268+
`);
269+
// Section 2 is not returned.
270+
expect(res.getAttribute("id")).toEqual("section1");
271+
272+
// TD elements or others which can not be direct children of a
273+
// <div> are not yet supported.
274+
// Also see: https://stackoverflow.com/a/494348/1337474
275+
res = dom.create_from_string(`<td></td>`);
276+
expect(res).toBeFalsy();
277+
278+
done();
279+
});
280+
});
252281
});

0 commit comments

Comments
 (0)