InnerHTML.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibWeb/DOM/Element.h>
  8. #include <LibWeb/DOM/ExceptionOr.h>
  9. #include <LibWeb/DOM/ShadowRoot.h>
  10. #include <LibWeb/DOMParsing/Algorithms.h>
  11. #include <LibWeb/HTML/HTMLTemplateElement.h>
  12. namespace Web::DOMParsing::InnerHTML {
  13. // https://w3c.github.io/DOM-Parsing/#dom-innerhtml-innerhtml
  14. static DOM::ExceptionOr<void> inner_html_setter(NonnullRefPtr<DOM::Node> context_object, String const& value)
  15. {
  16. // 1. Let context element be the context object's host if the context object is a ShadowRoot object, or the context object otherwise.
  17. // (This is handled in Element and ShadowRoot)
  18. NonnullRefPtr<DOM::Element> context_element = is<DOM::ShadowRoot>(*context_object) ? *verify_cast<DOM::ShadowRoot>(*context_object).host() : verify_cast<DOM::Element>(*context_object);
  19. // 2. Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and with context element.
  20. auto fragment_or_exception = parse_fragment(value, context_element);
  21. if (fragment_or_exception.is_exception())
  22. return fragment_or_exception.exception();
  23. auto fragment = fragment_or_exception.release_value();
  24. // 3. If the context object is a template element, then let context object be the template's template contents (a DocumentFragment).
  25. if (is<HTML::HTMLTemplateElement>(*context_object))
  26. context_object = verify_cast<HTML::HTMLTemplateElement>(*context_object).content();
  27. // 4. Replace all with fragment within the context object.
  28. context_object->replace_all(fragment);
  29. return {};
  30. }
  31. }