How to Set Text of an Element with JavaScript
JavaScript provides two ways of setting the text content of an element depending on whether the text to add contains HTML or not. In this tutorial, we will learn how to use both of these methods.
Using the innerText Property
If you have plain text content you can set it as the text of any element using the innerText
DOM property.
<div id="foo"></div>
document.getElementById('foo').innerText = 'Some text.';
<div id="foo">Some text.</div>
Using the innerHTML Property
The innerHTML
property allows you to add HTML content inside an element a have it render. Let's say we wanted to add a link as the text content of a div we could do it like this:
<div id="foo"></div>
document.getElementById('foo').innerHTML = '<a href="https://www.skillsugar.com/">SkillSugar</a>';
<div id="foo"><a href="https://www.skillsugar.com/">SkillSugar</a></div>
Conclusion
You now know how to set plain text and HTML as the text content of an element with JavaScript.