0

I'm starting in javascript. I have two questions in one. I would like to show the date in a specific 'id', And use multiple 'id' in a same function. (data will appear several times in the site)

As: id="date1" id="date2" id="date3"

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

I know I have to use this line but I do not know how to apply it:

document.getElementById("date").innerHTML
4
  • 2
    document.getElementById("date").innerText = today; Commented Jun 4, 2019 at 14:52
  • @RomanBobrik Did you mean textContent? innerText is nonstandard. Commented Jun 4, 2019 at 14:53
  • 3
    @MadaraUchiha It's not non-standard? developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText (simply "easily confused with" another element property). Commented Jun 4, 2019 at 14:53
  • Huh, so they did end up adding it. I still wouldn't use innerText because of its.... oddities. Mostly around linebreaks. Commented Jun 4, 2019 at 14:54

1 Answer 1

2

.innerHTML and its safer cousin .textContent are assignable properties which affect the DOM upon assigning.

document.getElementById("date").textContent = today;

will cause the DOM node which matches the getElementById("date") query (i.e. the element in the DOM with the id= attribute of date), to have its text replaced with the value of today.

The reason to prefer textContent over innerHTML is that textContent is less exposed to XSS attacks. (Only use .innerHTML when you intend to add HTML to a DOM node, and not plain text, see here and here for more details on that, although I'd wait until you have better established your JavaScript knowledge). When in doubt, use textContent over innerHTML.

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;

document.getElementById('date').textContent = today;
<div id="date"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.