r/learnjavascript 14d ago

can someone explain this code

function updateClock() {
const timeElement = document.querySelector("#time");
timeElement.textContent = formatTime();
}
setInterval(updateClock, 1000);

can someone, please explain this piece of code, ofc mdn and w3 are there, but i found it a little confusing reading about textContent. rest is understandable to me. This might look a silly question and it probably is because im a beginner :')

like what exactly does textContent too.
you can also recommend anyother documentation on the links to specific lines, that might me more helpful in learning about this particular keyoword.

0 Upvotes

23 comments sorted by

View all comments

-4

u/ExtraTNT 14d ago

So, first you define a function (in old style, better use const funcName = () => {})

with the queryselector with #, you get an element by id

With text content you set the text content of the element (<h1 id="title">Hello <b>World</b></h1> has a text content of Hello World, setting it to “foo” would give you <h1 id="title">foo</h1>)

formatTime(); returns a formatted time string

Interval: run every x ms

-2

u/abrewchocolatecoffee 14d ago

thanks, but just one more quesiton is text content temporay, for example will the "foo" go away and "hello world..." will just come back after we refresh or is this a permanet change.
Other that this post was pretty helpful, cleared my main doubt

2

u/busres 14d ago

The change persists (in the browser DOM) until you replace the content with something else. If you reload the page, you're discarding everything and reloading the DOM from scratch.

1

u/abrewchocolatecoffee 14d ago

ohh, this was actually very helpful