3

I have not been able to find information about whether it is possible to getComputedStyle of an element that is not in the browser DOM.

My testing suggests that elements not inserted in the browser DOM do not get a computed style.

var el = document.createElement("span")
el.id = "greeting"
el.textContent = "Hi there"
el.setAttribute("style", "background-color: yellow;")

console.log("Element in JS memory:", window.getComputedStyle(el).backgroundColor)

document.querySelector("body").appendChild(el)

console.log("Element in browser dom:", window.getComputedStyle(document.querySelector("#greeting")).backgroundColor)

But it does not strike me as unreasonable that it would be possible to ask the browser to calculate styles for documents or elements that in JavaScript memory. Or there might be some package that does this. But I haven't found any.

Is this possible (without having to write complex css computation logic myself)?

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    According to the spec (https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle) it must (at least?) be in the shadow tree. – Felix Kling Mar 23 '20 at 14:56
  • 2
    The problem is the computed style depends on the position of the element in the DOM. For example, if the element is a div and it is in a div of width 100px then the element's width is 100px but if it is in the body then the element's width is the window width. It is literally not possible to compute a style without knowing where in the document an element is. – slebetman Mar 23 '20 at 16:38
  • @slebetman true, but if i want to know - let's say - just a value from CSS file for a specific selector, what should I do? – Alexander May 15 '22 at 16:04

0 Answers0