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:
xxxxxxxxxx
1
element.textContent = 'Example text...';
or:
xxxxxxxxxx
1
element.innerText = 'Example text...';
DO NOT USE innerHTML
if it is not necessary !!!:
xxxxxxxxxx
1
element.innerHTML = 'Example text...';
Warning:
innerHTML
may lead to dangerous HTML injection (usetextContent
orinnerText
).
In this section, we present a practical example of how to set div
element text dynamically by setting textContent
value.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var myDiv = document.createElement('div'); // creates new div element
7
8
myDiv.textContent = 'Example text...'; // set text for the element
9
10
// You can also use:
11
// myDiv.innerText = 'Example text...';
12
13
document.body.appendChild(myDiv); // appends element to the document body
14
15
</script>
16
</body>
17
</html>
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-div"></div>
5
<script>
6
7
let myDiv = document.querySelector('#my-div'); // gets element by id
8
9
myDiv.textContent = 'Example text...'; // sets new element's text
10
11
// You can also use:
12
// myDiv.innerText = 'Example text...';
13
14
</script>
15
</body>
16
</html>