1

I can console.log(2), but it didn't work when I want to show the opacity of the 'div'?

let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click', function() {
    console.log(obj.style.opacity);
    console.log(2);
})       
<div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
<button id="fade-btn">click</button>
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
jack petton
  • 49
  • 1
  • 10
  • 2
    Please refer this https://stackoverflow.com/questions/50645188/why-element-style-always-return-empty-while-providing-styles-in-css – chintuyadavsara Nov 01 '18 at 06:59

4 Answers4

1

try this

console.log( window.getComputedStyle(obj).getPropertyValue('opacity');
suresh bambhaniya
  • 1,687
  • 1
  • 10
  • 20
0

You have to set opacity to see it

let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click',function(){
       console.log(obj.style.opacity);
});
     
#fade-obj{
width:300px;
height:300px;
background:#000;
}
<div id="fade-obj" style="opacity:1"></div>
<button id="fade-btn">click</button>

Or use window.getComputedStyle(obj).getPropertyValue('opacity')

let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click',function(){
       console.log(window.getComputedStyle(obj).getPropertyValue('opacity'));
});
#fade-obj{
width:300px;
height:300px;
background:#000;
}
<div id="fade-obj"></div>
<button id="fade-btn">click</button>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
0

Add some default opacity value in order to check value . say opacity:2

console.log(document.getElementById('fade-obj').style.opacity);
<div id="fade-obj" style="width:30px;height:30px;background:#000;opacity:2"></div>
manikant gautam
  • 3,521
  • 1
  • 17
  • 27
0

The problem is that when you don't set the opacity, the browser sets it for you. So the opacity is not from the CSS itself. Rather it is computed. Get value using:

let obj = document.getElementById('fade-obj');
window.getComputedStyle(obj).getPropertyValue('opacity');
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55