getComputedStyle function

CssStyleDeclaration getComputedStyle({
  1. Element? parent,
  2. Element? element,
  3. String? classes,
  4. String? style,
  5. bool? hidden,
})

Returns a CssStyleDeclaration from an element.

Implementation

CssStyleDeclaration getComputedStyle(
    {Element? parent,
    Element? element,
    String? classes,
    String? style,
    bool? hidden}) {
  parent ??= document.body;
  hidden ??= true;

  element ??= DivElement();

  var prevHidden = element.hidden;

  element.hidden = hidden;

  if (classes != null && classes.isNotEmpty) {
    var allClasses =
        classes.split(RegExp(r'\s+')).where((s) => s.isNotEmpty).toList();
    for (var c in allClasses) {
      element.classes.add(c);
    }
  }

  if (style != null && style.isNotEmpty) {
    element.style.cssText = style;
  }

  parent!.children.add(element);

  var computedStyle = element.getComputedStyle();
  var cssText = computedStyle.cssText;

  var computedStyle2 = CssStyleDeclaration();
  computedStyle2.cssText = cssText;

  element.remove();

  element.hidden = prevHidden;

  return computedStyle2;
}