0

I was trying to show battery level using javascript where I found an unexpected error. My codes:

const  percentage = document.getElementById('percentage');
const percent = document.getElementById('percent');
navigator.getBattery().then(function(battery){
                percentage.style.width = battery.level * 100 + '%' ;
                percent.innerHTML = battery.level * 100  + '%';
                alert(battery.level);
});

I got an error saying, >TypeError: cannot read the proper 'style' of null When I try putting the 4th and 5th line on the comment e.g.

// 
  percentage.style.width = battery.level * 100 + '%' ;

First, I got another error message saying:

TypeError: Cannot set the property 'innerHTML' of null Then, the alert() gave the correct battery level

Kashif
  • 480
  • 4
  • 11
Liberty
  • 1
  • 3
  • Hi, Try using something like: `const percentage = document.getElementById('percentage')[0];` – Yash Maheshwari May 07 '21 at 11:18
  • @YashMaheshwari It won't work since `getElementById` returns the first element that matches the given id, not an array. – TechySharnav May 07 '21 at 11:23
  • Make sure there is an element with an id="percentage" on the DOM when the code executes. You can also try document.querySelector("#percentage") – Andrei Ionita May 07 '21 at 11:39
  • I was sure about my html contents, I faced the problem in thr javascript, but I have solved it by my own. Thank you very much for your response – Liberty May 11 '21 at 05:26

1 Answers1

0

I have found it's solution. Instead of using variables, I wrote the whole statement before .style and that worked. Final code:

                            setInterval(function(){ navigator.getBattery().then(function(battery){
                document.getElementById('percentage').style.width = battery.level * 100 + '%' ;
                document.getElementById('percent').innerHTML = battery.level * 100  + '%';
});
}, 10);
Liberty
  • 1
  • 3