ParentNode.cpp 1.9 KB

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