1

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?

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

I used jQuery to get the value...

function onS(obj) {
  var logo = $('.logo');
  var value = logo.css('marginLeft');
  alert(value);
}
.logo { display: block; position: relative; margin-left: 40px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo" onmouseover="onS(this)">Test!</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.