Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ Parse the data provided, wrap the result in a new node, and return the root of t
noscript: true, // keep text content when parsing
style: true, // keep text content when parsing
pre: true // keep text content when parsing
}
},
closeAllOnClosing: false // Close all non-closed tags when containing element closes
}
```

Expand Down
17 changes: 17 additions & 0 deletions src/nodes/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,7 @@ export interface Options {
*/
closingSlash?: boolean;
};
closeAllByClosing?: boolean;
}

const frameflag = 'documentfragmentcontainer';
Expand Down Expand Up @@ -1227,6 +1228,22 @@ export function base_parse(data: string, options = {} as Partial<Options>) {
}
}
}
if (options.closeAllByClosing === true) {
// If tag was opened, close all nested tags
let i;
for (i = stack.length - 2; i >= 0; i--) {
if (stack[i].rawTagName === tagName) break;
}
if (i >= 0) {
while (stack.length > i) {
// Update range end for closed tag
(<[number, number]>currentParent.range)[1] = createRange(-1, Math.max(lastTextPos, tagEndPos))[1];
stack.pop();
currentParent = arr_back(stack);
}
continue;
}
}
// Use aggressive strategy to handle unmatching markups.
break;
}
Expand Down
16 changes: 16 additions & 0 deletions test/tests/unclosedtags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { parse, valid } = require('@test/test-target');

describe('Unclosed tags', function () {
it('Unclosed tags should be closed at end of parent element', function () {
const html = '<p>not bold<b>bold</p><p>more</p>';
valid(html, { closeAllByClosing: true }).should.be.true();
const root = parse(html, { closeAllByClosing: true });
root.outerHTML.should.equal('<p>not bold<b>bold</b></p><p>more</p>');
});
it('Nested unclosed tags should be closed at end of parent element', function () {
const html = '<p>not bold<b>bold<i>bold italic</p><p>more</p>';
valid(html, { closeAllByClosing: true }).should.be.true();
const root = parse(html, { closeAllByClosing: true });
root.outerHTML.should.equal('<p>not bold<b>bold<i>bold italic</i></b></p><p>more</p>');
});
});