dom: add element.replaceChildren

This commit is contained in:
Pierre Tachoire
2023-12-13 15:51:48 +01:00
parent 3af716d934
commit 84aad08806
2 changed files with 34 additions and 0 deletions

View File

@@ -315,6 +315,33 @@ pub const Element = struct {
}
}
// TODO according with https://dom.spec.whatwg.org/#parentnode, the
// function must accept either node or string.
// blocked by https://github.com/lightpanda-io/jsruntime-lib/issues/114
pub fn _replaceChildren(self: *parser.Element, nodes: ?Variadic(*parser.Node)) !void {
// if (nodes == null) return;
// if (nodes.?.slice.len == 0) return;
const nself = parser.elementToNode(self);
// remove existing children
if (try parser.nodeHasChildNodes(nself)) {
const children = try parser.nodeGetChildNodes(nself);
const ln = try parser.nodeListLength(children);
var i: u32 = 0;
while (i < ln) {
defer i += 1;
const child = try parser.nodeListItem(children, i) orelse continue;
_ = try parser.nodeRemoveChild(nself, child);
}
}
// add new children
for (nodes.?.slice) |node| {
_ = try parser.nodeAppendChild(nself, node);
}
}
pub fn deinit(_: *parser.Element, _: std.mem.Allocator) void {}
};

View File

@@ -620,6 +620,13 @@ pub fn nodeSetTextContent(node: *Node, value: []const u8) !void {
try DOMErr(err);
}
pub fn nodeGetChildNodes(node: *Node) !*NodeList {
var nlist: ?*NodeList = undefined;
const err = nodeVtable(node).dom_node_get_child_nodes.?(node, &nlist);
try DOMErr(err);
return nlist.?;
}
pub fn nodeAppendChild(node: *Node, child: *Node) !*Node {
var res: ?*Node = undefined;
const err = nodeVtable(node).dom_node_append_child.?(node, child, &res);