Sometimes, we want to get margin value of a div in plain JavaScript.
In this article, we’ll look at how to get margin value of a div in plain JavaScript.
How to get margin value of a div in plain JavaScript?
To get margin value of a div in plain JavaScript, we use the getComputedStyle method.
For instance, we write
const p = document.getElementById("target");
const style = window.getComputedStyle(p);
console.log(style.marginTop);
to select the element we want to get the margin for with getElementById.
Then we call getComputedStyle with p to return an object with the computed styles.
And then we get the margin top value with style.marginTop in pixels.
Conclusion
To get margin value of a div in plain JavaScript, we use the getComputedStyle method.