Jelajahi Sumber

LibWeb: Add an accessor for the document's title element

Timothy Flynn 2 tahun lalu
induk
melakukan
43b3673198

+ 15 - 0
Userland/Libraries/LibWeb/DOM/Document.cpp

@@ -631,6 +631,21 @@ HTML::HTMLHeadElement* Document::head()
     return html->first_child_of_type<HTML::HTMLHeadElement>();
 }
 
+// https://html.spec.whatwg.org/multipage/dom.html#the-title-element-2
+JS::GCPtr<HTML::HTMLTitleElement> Document::title_element()
+{
+    // The title element of a document is the first title element in the document (in tree order), if there is one, or
+    // null otherwise.
+    JS::GCPtr<HTML::HTMLTitleElement> title_element = nullptr;
+
+    for_each_in_subtree_of_type<HTML::HTMLTitleElement>([&](auto& title_element_in_tree) {
+        title_element = title_element_in_tree;
+        return IterationDecision::Break;
+    });
+
+    return title_element;
+}
+
 HTML::HTMLElement* Document::body()
 {
     auto* html = html_element();

+ 6 - 0
Userland/Libraries/LibWeb/DOM/Document.h

@@ -147,6 +147,7 @@ public:
 
     HTML::HTMLHtmlElement* html_element();
     HTML::HTMLHeadElement* head();
+    JS::GCPtr<HTML::HTMLTitleElement> title_element();
     HTML::HTMLElement* body();
 
     HTML::HTMLHtmlElement const* html_element() const
@@ -159,6 +160,11 @@ public:
         return const_cast<Document*>(this)->head();
     }
 
+    JS::GCPtr<HTML::HTMLTitleElement const> title_element() const
+    {
+        return const_cast<Document*>(this)->title_element();
+    }
+
     HTML::HTMLElement const* body() const
     {
         return const_cast<Document*>(this)->body();