dom: implement getElementsByClassName

This commit is contained in:
Pierre Tachoire
2023-11-17 17:36:28 +01:00
parent e9edb8bab4
commit dd28204797
3 changed files with 48 additions and 0 deletions

View File

@@ -13,6 +13,7 @@ const Union = @import("element.zig").Union;
const Match = union(enum) {
matchByTagName: MatchByTagName,
matchByClassName: MatchByClassName,
pub fn match(self: Match, node: *parser.Node) bool {
switch (self) {
@@ -55,6 +56,37 @@ pub fn HTMLCollectionByTagName(root: *parser.Node, tag_name: []const u8) !HTMLCo
};
}
pub const MatchByClassName = struct {
classNames: []const u8,
fn init(classNames: []const u8) !MatchByClassName {
return MatchByClassName{
.classNames = classNames,
};
}
pub fn match(self: MatchByClassName, node: *parser.Node) bool {
var it = std.mem.splitAny(u8, self.classNames, " ");
const e = parser.nodeToElement(node);
while (it.next()) |c| {
if (!parser.elementHasClass(e, c)) {
return false;
}
}
return true;
}
};
pub fn HTMLCollectionByClassName(root: *parser.Node, classNames: []const u8) !HTMLCollection {
return HTMLCollection{
.root = root,
.match = Match{
.matchByClassName = try MatchByClassName.init(classNames),
},
};
}
// WEB IDL https://dom.spec.whatwg.org/#htmlcollection
// HTMLCollection is re implemented in zig here because libdom
// dom_html_collection expects a comparison function callback as arguement.