Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

got (an empty string) when trying to get marginTop value in js

Tags:

javascript

<style>
  body { margin: 10px }
</style>
<body>
  <script> 
    console.log(document.body.style.marginTop); 
  </script>
</body>

Question:

in firefox->console it shows : (an empty string), why?

like image 564
user2507818 Avatar asked Jul 01 '13 07:07

user2507818


2 Answers

window.getComputedStyle(document.body).marginTop

document.body.style returns inline styles

like image 151
karaxuna Avatar answered Sep 24 '22 16:09

karaxuna


You can do it like this:

var e = document.getElementsByTagName('body')[0],
style = window.getComputedStyle(e),
marginTop = style.getPropertyValue('margin-top');

console.log(marginTop); 

Related question and answer, see here: Using JavaScript to read html / body tag margin-top

like image 44
Matthias Holdorf Avatar answered Sep 24 '22 16:09

Matthias Holdorf