node: textContent must ignore comments for elements

This commit is contained in:
Pierre Tachoire
2025-12-06 18:19:44 +01:00
parent e41d53019f
commit f5d3dede6b
2 changed files with 28 additions and 6 deletions

View File

@@ -1,6 +1,12 @@
<!DOCTYPE html>
<script src="../testing.js"></script>
<div id=id1>d1 <p>hello</p></div>
<div id=id2>
<style>h1 { font-size: 1em; }</style>
<!-- this is a comment -->
This is a <br>
text
</div>
<script id=element>
const div = $('#id1');
@@ -8,6 +14,9 @@
div.textContent = 'world <p>!</p>';
testing.expectEqual('world <p>!</p>', div.textContent);
const div2 = $('#id2');
testing.expectEqual("\n h1 { font-size: 1em; }\n \n This is a \n text\n", div2.textContent);
</script>
<script id=document>
@@ -28,8 +37,8 @@
const attr = div.getAttributeNode('id');
testing.expectEqual('id1', attr.value);
testing.expectEqual('id1', attr.textContent);
attr.textContent = 'id2';
testing.expectEqual('id2', attr.value);
testing.expectEqual('id2', attr.textContent);
testing.expectEqual(div, $('#id2'));
attr.textContent = 'attr2';
testing.expectEqual('attr2', attr.value);
testing.expectEqual('attr2', attr.textContent);
testing.expectEqual(div, $('#attr2'));
</script>

View File

@@ -171,7 +171,20 @@ pub fn childNodes(self: *const Node, page: *Page) !*collections.ChildNodes {
pub fn getTextContent(self: *Node, writer: *std.Io.Writer) error{WriteFailed}!void {
switch (self._type) {
.element => |el| return el.getInnerText(writer),
.element => {
var it = self.childrenIterator();
while (it.next()) |child| {
// ignore comments and TODO processing instructions.
switch (child._type) {
.cdata => |c| switch (c._type) {
.comment => continue,
.text => {},
},
else => {},
}
try child.getTextContent(writer);
}
},
.cdata => |c| try writer.writeAll(c.getData()),
.document => {},
.document_type => {},
@@ -719,7 +732,7 @@ pub const JsApi = struct {
switch (self._type) {
.element => |el| {
var buf = std.Io.Writer.Allocating.init(page.call_arena);
try el.getInnerText(&buf.writer);
try el.asNode().getTextContent(&buf.writer);
return buf.written();
},
.cdata => |cdata| return cdata.getData(),