1

I have a basic CSS problem, that I don't know is really a basic or is it something else.

Here is the HTML.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class='test1'>Test1</div>
</body>
</html>

Here is the CSS.

.test1 {
  width: 50px;
  height: 50px;
  border: 1px solid red;
  margin: 5px;
}

As we can see I have an div element having a class test1 on it with margin property as 5px. Now if I want to get the margin value on the div element how will I get it?

And just a tip, writing below JS won't do anything, as there is no style attribute in the div, margin is added to the div by css class test1.

const test1 = document.getElementsByClassName("test1")[0];
console.log(test1.style.margin);

Here is the JSBIN for the above scenerio.

Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53
  • As mentioned in the Question there is no style atrribute at all in the div element, so writing document.getElementsByClassName("test1")[0].style.margin won't work. – Divyanshu Rawat Oct 18 '19 at 12:36
  • @Zuber what are you trying to say, I need to grab the margin property in the css attached to the div. – Divyanshu Rawat Oct 18 '19 at 12:37
  • @Zuber that what question is I don't want to give style attribute, just read the Question carefully and all the comments then please write your thoughts on it. – Divyanshu Rawat Oct 18 '19 at 12:41
  • @Zuber please just read the last few lines starting from And just a tip, writing below JS won't do anything, as there is no style attribute in the div, margin is added to the div by css class test1. That is what I am trying to say on those lines, that's why the answer posted doesn't involve adding inline style attribute. – Divyanshu Rawat Oct 18 '19 at 12:49

1 Answers1

1

You can try with Window.getComputedStyle():

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.

const test1 = document.getElementsByClassName("test1")[0];
console.log(getComputedStyle(test1).margin);
.test1 {
  width: 50px;
  height: 50px;
  border: 1px solid red;
  margin: 5px;
}
<div class='test1'>Test1</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59