0

I have a div with a background image positioned at X 0px and Y 0px position. Now I want to return this values in a console.log, but the console shows me a blank entry. I tried with alert and is the same.

Why is this happening?

var myDiv = document.getElementsByClassName('myDiv')[0];

console.log(myDiv.style.backgroundPositionY);
.myDiv{
  width:200px; height:200px;
  background:blue;
  background-image:url(http://www.shunvmall.com/data/out/141/46916550-landscape-pictures.jpeg);
  background-repeat:no-repeat;
 background-position:0px 0px;
 background-size:cover;
}
<div class="myDiv"></div>
GhostOrder
  • 586
  • 7
  • 21
  • .style only provides the inline style values applied to the element. See here for more info: http://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript – CSturgess May 04 '17 at 22:04

3 Answers3

2

The style object on an element only reflects the styles directly applied to the element. Styles applied by classes do not show there. To get those, use getComputedStyle (standard) or currentStyle (IE-specific):

Standard:

console.log(getComputedStyle(myDiv).backgroundPositionY);

IE-specific:

console.log(myDiv.currentStyle.backgroundPositionY);

Example of standard:

var myDiv = document.getElementsByClassName('myDiv')[0];

console.log(getComputedStyle(myDiv).backgroundPositionY);
.myDiv{
  width:200px; height:200px;
  background:blue;
  background-image:url(http://www.shunvmall.com/data/out/141/46916550-landscape-pictures.jpeg);
  background-repeat:no-repeat;
 background-position:0px 0px;
 background-size:cover;
}
<div class="myDiv"></div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

To achieve expected result, use below

var divElem = document.querySelector('.myDiv');
style = getComputedStyle(divElem)
console.log(style.backgroundPositionY);

Codepen -https://codepen.io/nagasai/pen/MmEjjr?editors=1111

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
0

The following JavaScript works:

var myDiv = document.getElementsByClassName('myDiv')[0],
    _tmp =     window.getComputedStyle(myDiv,null).backgroundPosition.trim().split(/\s+/),
    positions = {
        'left' : _tmp[0],
        'top' : _tmp[1]
    };
console.log(positions, positions.left, positions.top);

reference

Community
  • 1
  • 1
alessandrio
  • 4,282
  • 2
  • 29
  • 40