getComputedStyle function

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

Returns a CSSStyleDeclaration from an element.

Implementation

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

  element ??= HTMLDivElement();

  var prevHidden = element.hidden;

  element.hidden = hidden.toJS;

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

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

  parent!.appendChild(element);

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

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

  element.remove();

  element.hidden = prevHidden;

  return computedStyle2;
}