HTMLCollection.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/DOM/Element.h>
  7. #include <LibWeb/DOM/HTMLCollection.h>
  8. #include <LibWeb/DOM/ParentNode.h>
  9. namespace Web::DOM {
  10. HTMLCollection::HTMLCollection(ParentNode& root, Function<bool(Element const&)> filter)
  11. : m_root(root)
  12. , m_filter(move(filter))
  13. {
  14. }
  15. HTMLCollection::~HTMLCollection()
  16. {
  17. }
  18. Vector<NonnullRefPtr<Element>> HTMLCollection::collect_matching_elements()
  19. {
  20. Vector<NonnullRefPtr<Element>> elements;
  21. m_root->for_each_in_inclusive_subtree_of_type<Element>([&](auto& element) {
  22. if (m_filter(element))
  23. elements.append(element);
  24. return IterationDecision::Continue;
  25. });
  26. return elements;
  27. }
  28. size_t HTMLCollection::length()
  29. {
  30. return collect_matching_elements().size();
  31. }
  32. Element* HTMLCollection::item(size_t index)
  33. {
  34. auto elements = collect_matching_elements();
  35. if (index >= elements.size())
  36. return nullptr;
  37. return elements[index];
  38. }
  39. Element* HTMLCollection::named_item(FlyString const& name)
  40. {
  41. if (name.is_null())
  42. return nullptr;
  43. auto elements = collect_matching_elements();
  44. // First look for an "id" attribute match
  45. if (auto it = elements.find_if([&](auto& entry) { return entry->attribute(HTML::AttributeNames::id) == name; }); it != elements.end())
  46. return *it;
  47. // Then look for a "name" attribute match
  48. if (auto it = elements.find_if([&](auto& entry) { return entry->name() == name; }); it != elements.end())
  49. return *it;
  50. return nullptr;
  51. }
  52. }