Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an easier more efficient way I can manipulate the contents of the paragraph tag below?

So I have a timer variable that points to a paragraph in html.
Now I want to change the contents of this paragraph to display time

timer.innerHTML = hr + ":" + min;

Note: hr and min are variables that store the current time.

So, in order to avoid a situation where the time shows as
"9:7" when it’s 09:07am, I added a bunch of if statements

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If(hr < 10){
    timer.innerHTML = "0" + hr + ":" + min;
} 
If (min < 10){
    timer.innerHTML = hr + ":" + min;
}

However, I want to do so for hours, minutes, and seconds aswell.
Is there a more efficient way to do this rather than with a bunch of if statements.
Because it might become quite tedious to write if statements for every possiblity.

>Solution :

Try this, with a ternary conditional operator (see the docs on MDN for help):

time.innerHTML = (hr < 10 ? '0' : '') + hr + ':' + (min < 10 ? '0' : '') + min;

Here’s the MDN documentation for the conditional operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading