diff --git a/js/src/html/beautifier.js b/js/src/html/beautifier.js
index 6a70a4111..50a16f768 100644
--- a/js/src/html/beautifier.js
+++ b/js/src/html/beautifier.js
@@ -778,8 +778,8 @@ Beautifier.prototype._do_optional_end_element = function(parser_token) {
} else if (parser_token.tag_name === 'th' || parser_token.tag_name === 'td') {
// A td element’s end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
// A th element’s end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
- result = result || this._tag_stack.try_pop('td', ['tr']);
- result = result || this._tag_stack.try_pop('th', ['tr']);
+ result = result || this._tag_stack.try_pop('td', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
+ result = result || this._tag_stack.try_pop('th', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
}
// Start element omission not handled currently
diff --git a/js/test/generated/beautify-html-tests.js b/js/test/generated/beautify-html-tests.js
index bd11af1ec..0bf0f857f 100644
--- a/js/test/generated/beautify-html-tests.js
+++ b/js/test/generated/beautify-html-tests.js
@@ -6207,6 +6207,29 @@ function run_html_tests(test_obj, Urlencoded, js_beautify, html_beautify, css_be
'