Skip to content

Commit 4593b12

Browse files
committed
solve multiple comment scenarios
1 parent b4e9836 commit 4593b12

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

lib/parse.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,24 @@ module.exports = function parse(html, options) {
2323
}
2424
}
2525
var isOpen = tag.charAt(1) !== '/';
26+
var isComment = tag.startsWith('<!--');
2627
var start = index + tag.length;
2728
var nextChar = html.charAt(start);
2829
var parent;
2930

31+
if (isComment) {
32+
var comment = parseTag(tag)
33+
34+
// if we're at root, push new base node
35+
if (level < 0) {
36+
result.push(comment);
37+
return result
38+
}
39+
parent = arr[level]
40+
parent.children.push(comment)
41+
return result
42+
}
43+
3044
if (isOpen) {
3145
level++;
3246

test/parse.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,53 @@ test('parse', function (t) {
8484
}]);
8585
t.equal(html, HTML.stringify(parsed));
8686

87+
html = '<div><h2>Comment below this header</h2><!-- just a comment node --><!-- subsequent comment node --></div>';
88+
parsed = HTML.parse(html);
89+
t.deepEqual(parsed, [{
90+
name: 'div',
91+
type: 'tag',
92+
attrs: {},
93+
voidElement: false,
94+
children: [{
95+
attrs: {},
96+
name: 'h2',
97+
type: 'tag',
98+
voidElement: false,
99+
children: [{
100+
content: 'Comment below this header',
101+
type: 'text'
102+
}]
103+
},
104+
{
105+
type: 'comment' ,
106+
comment: ' just a comment node ',
107+
},{
108+
type: 'comment',
109+
comment: ' subsequent comment node '
110+
}]
111+
}]);
112+
t.equal(html, HTML.stringify(parsed));
113+
114+
html = '<div><h2><!-- comment inside h2 tag --></h2></div>';
115+
parsed = HTML.parse(html);
116+
t.deepEqual(parsed, [{
117+
name: 'div',
118+
type: 'tag',
119+
attrs: {},
120+
voidElement: false,
121+
children: [{
122+
attrs: {},
123+
name: 'h2',
124+
type: 'tag',
125+
voidElement: false,
126+
children: [{
127+
type: 'comment' ,
128+
comment: ' comment inside h2 tag ',
129+
}]
130+
}]
131+
}]);
132+
t.equal(html, HTML.stringify(parsed));
133+
87134
html = '<!---->'
88135
parsed = HTML.parse(html);
89136
t.deepEqual(parsed, [{

0 commit comments

Comments
 (0)