0

So, I want to fetch the top computed style of a <div> and put it into a variable. However, that <div> is not yet in the DOM. It will be appended to the DOM by a JavaScript event later (once the user triggers the .onclick() event).

To do that, I tried this: let style = getComputedStyle(element).top;

However, that won't work since element is not in the DOM yet. The following error appears if I attempt to do so:

Error

So, how can I fetch the top style of a specific element even if that element isn't in the DOM yet?

2
  • 1
    You could add it to the DOM with HTML "hidden" tag. That was it wont display on page but you can its styles. Commented Mar 25, 2020 at 16:24
  • i tried that, it didn't work, still got the error. i think ill just have to work around this fact by putting the variable once the click event is fired and element has been appended to DOM. thank tho :) Commented Mar 25, 2020 at 16:34

1 Answer 1

1

You can't. You can only get the computed style of an element in the DOM, since its computed style depends on where it is, what's around it, and what styles are in place.

Instead, if you know the characteristics of the DOM element and where it will be, you can add a placeholder for it in the same place, with the same classes, etc.; then get its style, get top from that, then remove it. The user will never see it if you do that all in one sequence without yielding back to the event loop.

Sign up to request clarification or add additional context in comments.

1 Comment

oh ok... I guess ill just have to work around it.. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.