diff --git a/Libraries/LibHTML/DOM/Node.cpp b/Libraries/LibHTML/DOM/Node.cpp
index d1b70fe1cd..630a4cded9 100644
--- a/Libraries/LibHTML/DOM/Node.cpp
+++ b/Libraries/LibHTML/DOM/Node.cpp
@@ -56,16 +56,12 @@ RefPtr Node::create_layout_tree(const StyleResolver& resolver, const
const HTMLAnchorElement* Node::enclosing_link_element() const
{
- if (is(*this))
- return static_cast(this);
- return parent() ? parent()->enclosing_link_element() : nullptr;
+ return first_ancestor_of_type();
}
const HTMLElement* Node::enclosing_html_element() const
{
- if (is_html_element())
- return static_cast(this);
- return parent() ? parent()->enclosing_html_element() : nullptr;
+ return first_ancestor_of_type();
}
String Node::text_content() const
diff --git a/Libraries/LibHTML/DOM/Node.h b/Libraries/LibHTML/DOM/Node.h
index d4213f29a4..5d4eac4c3a 100644
--- a/Libraries/LibHTML/DOM/Node.h
+++ b/Libraries/LibHTML/DOM/Node.h
@@ -50,6 +50,9 @@ public:
template
const T* first_child_of_type() const;
+ template
+ const T* first_ancestor_of_type() const;
+
virtual void inserted_into(Node&) {}
virtual void removed_from(Node&) {}
@@ -130,3 +133,13 @@ inline const T* Node::first_child_of_type() const
}
return nullptr;
}
+
+template
+inline const T* Node::first_ancestor_of_type() const
+{
+ for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
+ if (is(*ancestor))
+ return to(ancestor);
+ }
+ return nullptr;
+}