EN
JavaScript - set element text dynamically
3
points
In this article, we would like to show you how to set element text dynamically in JavaScript.
Quick solution:
element.textContent = 'Example text...';
or:
element.innerText = 'Example text...';
DO NOT USE innerHTML if it is not necessary !!!:
element.innerHTML = 'Example text...';
Warning:
innerHTMLmay lead to dangerous HTML injection (usetextContentorinnerText).
Practical examples
In this section, we present a practical example of how to set div element text dynamically by setting textContent value.
1. On new div element
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
var myDiv = document.createElement('div'); // creates new div element
myDiv.textContent = 'Example text...'; // set text for the element
// You can also use:
// myDiv.innerText = 'Example text...';
document.body.appendChild(myDiv); // appends element to the document body
</script>
</body>
</html>
2. on existing div element
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="my-div"></div>
<script>
let myDiv = document.querySelector('#my-div'); // gets element by id
myDiv.textContent = 'Example text...'; // sets new element's text
// You can also use:
// myDiv.innerText = 'Example text...';
</script>
</body>
</html>