0

I am kind of new to Web Development and I was trying to access a property of and id.style in my site, but unfortunately there was no response in my program so I have uploaded my problem in this code. please also tell me how to change that value.

function myMove() {
  var elem = document.getElementById("container");
  alert(elem.style.top);

}
#container {
  width: 400px;
  height: 400px;
  top: 10px;
  position: relative;
  background: yellow;
}
<p><button onclick="myMove()">Click Me</button></p>
<div id="container"></div>
Vishnubly
  • 539
  • 1
  • 8
  • 17

1 Answers1

1

You may access the CSS value you want using window.getComputedStyle()

See MDN for more details

But what you may really want is element.offsetTop;

See MDN here for that

function myMove() {
  var elem = document.getElementById("container");
  var computedStyles = window.getComputedStyle(elem)
  var top = computedStyles.getPropertyValue('top')
  alert(top);
  alert(elem.offsetTop);
}
laruiss
  • 3,780
  • 1
  • 18
  • 29
  • thanks, but I also want to change that value, than in that case what should I do? – Vishnubly Feb 21 '20 at 21:34
  • Programmatically, you can only change `elem.style.top`, and you do so like this: `elem.style.top = '20px' // (or any valid CSS value)`. But that might not do what you expect. I suggest you post another question with a clearer goal. – laruiss Feb 21 '20 at 21:40