Selaa lähdekoodia

LibHTML: Add Node::first_ancestor_of_type<T>()

Here's another helper for finding the first ancestor of a Node of a
specific type.
Andreas Kling 5 vuotta sitten
vanhempi
commit
a239ef34d5
2 muutettua tiedostoa jossa 15 lisäystä ja 6 poistoa
  1. 2 6
      Libraries/LibHTML/DOM/Node.cpp
  2. 13 0
      Libraries/LibHTML/DOM/Node.h

+ 2 - 6
Libraries/LibHTML/DOM/Node.cpp

@@ -56,16 +56,12 @@ RefPtr<LayoutNode> Node::create_layout_tree(const StyleResolver& resolver, const
 
 const HTMLAnchorElement* Node::enclosing_link_element() const
 {
-    if (is<HTMLAnchorElement>(*this))
-        return static_cast<const HTMLAnchorElement*>(this);
-    return parent() ? parent()->enclosing_link_element() : nullptr;
+    return first_ancestor_of_type<HTMLAnchorElement>();
 }
 
 const HTMLElement* Node::enclosing_html_element() const
 {
-    if (is_html_element())
-        return static_cast<const HTMLElement*>(this);
-    return parent() ? parent()->enclosing_html_element() : nullptr;
+    return first_ancestor_of_type<HTMLElement>();
 }
 
 String Node::text_content() const

+ 13 - 0
Libraries/LibHTML/DOM/Node.h

@@ -50,6 +50,9 @@ public:
     template<typename T>
     const T* first_child_of_type() const;
 
+    template<typename T>
+    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<typename T>
+inline const T* Node::first_ancestor_of_type() const
+{
+    for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
+        if (is<T>(*ancestor))
+            return to<T>(ancestor);
+    }
+    return nullptr;
+}