JavaScript DOM update page element text contents

To update the text content of an element in the DOM (Document Object Model) using JavaScript, you can use several methods depending on the situation and the specific element you want to update. Here are some common approaches:

  1. Using textContent property: You can update the text content of an element by accessing its textContent property and setting it to the desired text.
<div id="myElement">This is the initial text.</div>
const element = document.getElementById('myElement');
element.textContent = 'This is the updated text.';
  1. Using innerText property: Similar to textContent, you can also use the innerText property to update the text content of an element. However, note that innerText respects CSS styling and may not include text that is hidden by CSS.
const element = document.getElementById('myElement');
element.innerText = 'This is the updated text with CSS styling considered.';
  1. Using innerHTML property: If you need to update the text content along with HTML tags, you can use the innerHTML property. Be cautious when using this method, as it can introduce security vulnerabilities if the content is not properly sanitized.
<div id="myElement">This is the initial text.</div>
const element = document.getElementById('myElement');
element.innerHTML = '<p>This is the <strong>updated</strong> text with HTML tags.</p>';
  1. Using innerText or textContent with innerText property for specific cases: If you need to update the text content of specific elements within a container, you can use the querySelector method to select the element and then update its text content.
<div id="container">
  <p class="update-me">This is the initial paragraph.</p>
</div>
const paragraph = document.querySelector('#container .update-me');
paragraph.textContent = 'This is the updated paragraph.';
// or
paragraph.innerText = 'This is the updated paragraph with CSS styling considered.';

Choose the appropriate method based on your requirements. If you are updating plain text, textContent is generally recommended as it is more performant and won’t be affected by potential issues with HTML tags. If you need to work with HTML content, use innerHTML but be cautious about potential security risks if the content comes from untrusted sources.