diff --git a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp
index 03964f01ec..5c1fb0447f 100644
--- a/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp
+++ b/Libraries/LibWeb/Parser/HTMLDocumentParser.cpp
@@ -472,11 +472,7 @@ void HTMLDocumentParser::close_a_p_element()
if (current_node().tag_name() != "p") {
PARSE_ERROR();
}
- for (;;) {
- auto popped_element = m_stack_of_open_elements.pop();
- if (popped_element->tag_name() == "p")
- break;
- }
+ m_stack_of_open_elements.pop_until_an_element_with_tag_name_has_been_popped("p");
}
void HTMLDocumentParser::handle_after_body(HTMLToken& token)
@@ -729,7 +725,7 @@ void HTMLDocumentParser::handle_in_body(HTMLToken& token)
PARSE_ERROR();
}
- m_stack_of_open_elements.pop();
+ m_stack_of_open_elements.pop_until_an_element_with_tag_name_has_been_popped(token.tag_name());
return;
}
@@ -946,9 +942,7 @@ void HTMLDocumentParser::handle_in_cell(HTMLToken& token)
PARSE_ERROR();
}
- while (current_node().tag_name() != token.tag_name())
- m_stack_of_open_elements.pop();
- m_stack_of_open_elements.pop();
+ m_stack_of_open_elements.pop_until_an_element_with_tag_name_has_been_popped(token.tag_name())
m_list_of_active_formatting_elements.clear_up_to_the_last_marker();
@@ -1043,9 +1037,8 @@ void HTMLDocumentParser::handle_in_table(HTMLToken& token)
PARSE_ERROR();
return;
}
- while (current_node().tag_name() != "table")
- m_stack_of_open_elements.pop();
- m_stack_of_open_elements.pop();
+
+ m_stack_of_open_elements.pop_until_an_element_with_tag_name_has_been_popped("table");
reset_the_insertion_mode_appropriately();
return;
diff --git a/Libraries/LibWeb/Parser/StackOfOpenElements.cpp b/Libraries/LibWeb/Parser/StackOfOpenElements.cpp
index 0a57ee344e..ff07739702 100644
--- a/Libraries/LibWeb/Parser/StackOfOpenElements.cpp
+++ b/Libraries/LibWeb/Parser/StackOfOpenElements.cpp
@@ -94,4 +94,11 @@ bool StackOfOpenElements::contains(const Element& element) const
return false;
}
+void StackOfOpenElements::pop_until_an_element_with_tag_name_has_been_popped(const FlyString& tag_name)
+{
+ while (m_elements.last().tag_name() != tag_name)
+ pop();
+ pop();
+}
+
}
diff --git a/Libraries/LibWeb/Parser/StackOfOpenElements.h b/Libraries/LibWeb/Parser/StackOfOpenElements.h
index f551addde8..9918158dc9 100644
--- a/Libraries/LibWeb/Parser/StackOfOpenElements.h
+++ b/Libraries/LibWeb/Parser/StackOfOpenElements.h
@@ -57,6 +57,8 @@ public:
const NonnullRefPtrVector& elements() const { return m_elements; }
+ void pop_until_an_element_with_tag_name_has_been_popped(const FlyString&);
+
private:
bool has_in_scope_impl(const FlyString& tag_name, const Vector&) const;
bool has_in_scope_impl(const Element& target_node, const Vector&) const;