KenShiro KenShiro - 6 months ago 15
Javascript Question

Get value from CSS through querySelector

I am trying to get a specific value on CSS class through

querySelector
but still can't find a solution:

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



function onS(obj) {
var logo = document.querySelector('.logo');
var value = logo.style.marginLeft;
alert(value);
}

.logo { display: block; position: relative; margin-left: 40px; }

<div class="logo" onmouseover="onS(this)">Test!</div>





Is there 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>