KenShiro KenShiro - 5 months ago 9
jQuery Question

Get value from CSS trough querySelector

I am trying to get a value of specific valor of CSS class trough querySelector but still can't find a solution:

What I'm trying to get is the "40px" value:



<!DOCTYPE html>
<html>
<style type="text/css">
.logo {display: block; position: relative; margin-left: 40px;}
</style>
<head>
<title>Test</title>
</head>
<body>
<div class="logo" onmouseover="onS(this)">Test!</div>

<script type="text/javascript">
function onS(obj) {
var logo = document.querySelector('.logo');
var value = logo.style.marginLeft;
alert(value);
};
</script>

</body>
</html>





There is any way?

Answer

logo.style just looks at the inline style attribute, it doesn't get the computed style.

To get CSS values from a <style> tag or external stylesheet, use window.getComputedStyle()

function onS(obj) {
  var logo = document.querySelector('.logo');
  var value = window.getComputedStyle(logo).marginLeft;
  alert(value);
};
.logo {
  display: block;
  position: relative;
  margin-left: 40px;
}
<div class="logo" onmouseover="onS(this)">Test!</div>

Comments