1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 07:27:45 +00:00

LibWeb: Support Element.closest(selectors)

This commit is contained in:
Edwin Hoksberg 2022-02-15 20:41:51 +01:00 committed by Tim Flynn
parent 70ede2825e
commit c646afc26c
3 changed files with 28 additions and 0 deletions

View file

@ -358,6 +358,32 @@ DOM::ExceptionOr<bool> Element::matches(StringView selectors) const
return false;
}
// https://dom.spec.whatwg.org/#dom-element-closest
DOM::ExceptionOr<DOM::Element const*> Element::closest(StringView selectors) const
{
auto maybe_selectors = parse_selector(CSS::ParsingContext(static_cast<ParentNode&>(const_cast<Element&>(*this))), selectors);
if (!maybe_selectors.has_value())
return DOM::SyntaxError::create("Failed to parse selector");
auto matches_selectors = [](CSS::SelectorList const& selector_list, Element const* element) {
for (auto& selector : selector_list) {
if (!SelectorEngine::matches(selector, *element))
return false;
}
return true;
};
auto const selector_list = maybe_selectors.release_value();
for (auto* element = this; element; element = element->parent_element()) {
if (!matches_selectors(selector_list, element))
continue;
return element;
}
return nullptr;
}
ExceptionOr<void> Element::set_inner_html(String const& markup)
{
auto result = DOMParsing::inner_html_setter(*this, markup);

View file

@ -63,6 +63,7 @@ public:
RefPtr<DOMTokenList> const& class_list();
DOM::ExceptionOr<bool> matches(StringView selectors) const;
DOM::ExceptionOr<DOM::Element const*> closest(StringView selectors) const;
int client_top() const;
int client_left() const;

View file

@ -25,6 +25,7 @@ interface Element : Node {
[SameObject, PutForwards=value] readonly attribute DOMTokenList classList;
boolean matches(DOMString selectors);
Element? closest(DOMString selectors);
// legacy alias of .matches
[ImplementedAs=matches] boolean webkitMatchesSelector(DOMString selectors);