Element.html constructor

Element.html(
  1. String html
)

Implementation

factory Element.html(String html) {
  // TODO(jacobr): this method can be made more robust and performant.
  // 1) Cache the dummy parent elements required to use innerHTML rather than
  //    creating them every call.
  // 2) Verify that the html does not contain leading or trailing text nodes.
  // 3) Verify that the html does not contain both <head> and <body> tags.
  // 4) Detach the created element from its dummy parent.
  var parentTag = 'div';
  String? tag;
  final match = _startTagRegexp.firstMatch(html);
  if (match != null) {
    tag = match.group(1)!.toLowerCase();
    if (_customParentTagMap.containsKey(tag)) {
      parentTag = _customParentTagMap[tag]!;
    }
  }

  final fragment = parseFragment(html, container: parentTag);
  Element element;
  if (fragment.children.length == 1) {
    element = fragment.children[0];
  } else if (parentTag == 'html' && fragment.children.length == 2) {
    // You'll always get a head and a body when starting from html.
    element = fragment.children[tag == 'head' ? 0 : 1];
  } else {
    throw ArgumentError('HTML had ${fragment.children.length} '
        'top level elements but 1 expected');
  }
  element.remove();
  return element;
}