Categories
JavaScript Answers

How to get margin value of a div in plain JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *