Not able to display data in browser but able to display it in codepen

I am able to display the current date and time in codepen but not able to reciprocate it in the browser. Here is the codepen - https://codepen.io/adarsh88/pen/yLqVxJm. I am attaching the screenshot of my browser.
15 Replies
Mannix
Mannix2y ago
if it's working in codepen then you must be loading your js before the dom is loaded
Adarsh
AdarshOP2y ago
So what should I do, should I configure something? I am confused @mannix_
13eck
13eck2y ago
What does your HTML look like?
Mannix
Mannix2y ago
where is your js located in the head? at the bottom of the html ?
13eck
13eck2y ago
But probably adding the defer attribute to the script tag will work
Adarsh
AdarshOP2y ago
Its in the head
Mannix
Mannix2y ago
is it a link? to a js file?
13eck
13eck2y ago
Browsers parse files from top to bottom (unless told otherwise). So if your JS is being loaded before the DOM then there is no DOM to manipulate. The defer attribute tells the browsers "don't load this until the very end"
Adarsh
AdarshOP2y ago
No I have typed the code in a script tag Inside a head tag
Mannix
Mannix2y ago
then move it to the bottom above closing body tag
13eck
13eck2y ago
Oh, if its inline then you need to have it immediately before the closing body tag
Adarsh
AdarshOP2y ago
Okay I got it now, thanks so much for helping me out @mannix_ @cvanilla13eck
Mannix
Mannix2y ago
thumbup
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
13eck
13eck2y ago
You should use .innerText or .textContent instead of .innerHTML unless you're actually inserting, y'know, HTML. And if you're inserting HTML you should be creating and appending the elements instead of having JS parse a string into HTML and appending that to the DOM. Also, template literals are your friend, instead of using string concatenation. It's much less error prone and easier to read.
// string concatenation:
"Current Date and Time is: " + newDate.today() + " @ " + newDate.timeNow();

//template literal
`Current Date and Time is: ${newDate.today()}@${newDate.timeNow()}`;
// string concatenation:
"Current Date and Time is: " + newDate.today() + " @ " + newDate.timeNow();

//template literal
`Current Date and Time is: ${newDate.today()}@${newDate.timeNow()}`;
Want results from more Discord servers?
Add your server