ParentNode.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/CSS/Parser/Parser.h>
  7. #include <LibWeb/CSS/SelectorEngine.h>
  8. #include <LibWeb/DOM/ParentNode.h>
  9. #include <LibWeb/Dump.h>
  10. namespace Web::DOM {
  11. RefPtr<Element> ParentNode::query_selector(const StringView& selector_text)
  12. {
  13. auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text);
  14. if (!maybe_selectors.has_value())
  15. return {};
  16. auto selectors = maybe_selectors.value();
  17. for (auto& selector : selectors)
  18. dump_selector(selector);
  19. RefPtr<Element> result;
  20. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  21. for (auto& selector : selectors) {
  22. if (SelectorEngine::matches(selector, element)) {
  23. result = element;
  24. return IterationDecision::Break;
  25. }
  26. }
  27. return IterationDecision::Continue;
  28. });
  29. return result;
  30. }
  31. NonnullRefPtrVector<Element> ParentNode::query_selector_all(const StringView& selector_text)
  32. {
  33. auto maybe_selectors = parse_selector(CSS::ParsingContext(*this), selector_text);
  34. if (!maybe_selectors.has_value())
  35. return {};
  36. auto selectors = maybe_selectors.value();
  37. for (auto& selector : selectors)
  38. dump_selector(selector);
  39. NonnullRefPtrVector<Element> elements;
  40. for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  41. for (auto& selector : selectors) {
  42. if (SelectorEngine::matches(selector, element)) {
  43. elements.append(element);
  44. }
  45. }
  46. return IterationDecision::Continue;
  47. });
  48. return elements;
  49. }
  50. RefPtr<Element> ParentNode::first_element_child()
  51. {
  52. return first_child_of_type<Element>();
  53. }
  54. RefPtr<Element> ParentNode::last_element_child()
  55. {
  56. return last_child_of_type<Element>();
  57. }
  58. // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
  59. u32 ParentNode::child_element_count() const
  60. {
  61. u32 count = 0;
  62. for (auto* child = first_child(); child; child = child->next_sibling()) {
  63. if (is<Element>(child))
  64. ++count;
  65. }
  66. return count;
  67. }
  68. }