Languages
[Edit]
EN

JavaScript - set element text dynamically

3 points
Created by:
Kadeem-Craig
516

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: innerHTML may lead to dangerous HTML injection (use textContent or innerText).

 

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>

 

References

  1. Node.textContent - Web APIs | MDN
  2. HTMLElement.innerText - Web APIs | MDN
  3. Element.innerHTML - Web APIs | MDN

Alternative titles

  1. JavaScript - change HTML element text
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join