How to change a DOM node value

By

Learn how to change a DOM node value by setting its innerText property, and how to grab the element first with the Selectors API document.querySelector method.

~~~

To change the value of a DOM node, set its innerText property:

element.innerText = 'x'

To lookup the element, combine it with the Selectors API:

document.querySelector('#today .total')

Putting the two together, here’s a complete example. Say the page shows an order total:

<p>Total: <span id="total">$0.00</span></p>
const total = document.querySelector('#total')
total.innerText = '$45.99'

The text inside the span changes on screen immediately.

innerText vs textContent

textContent does a similar job:

total.textContent = '$45.99'

For setting a plain string, the two are almost interchangeable. The differences show up in the details.

innerText is aware of rendering. Reading it gives you the text as the user sees it, and setting it with newline characters turns them into <br> elements.

textContent works on the raw DOM. It includes text from hidden elements when reading, and it’s faster, since it doesn’t need any layout information.

What if the new value contains HTML?

innerText treats the string as plain text. Set it to '<b>paid</b>' and the page shows the tags literally.

To insert actual markup, use innerHTML:

total.innerHTML = '<b>$45.99</b>'

Be careful here. Never pass user-provided strings to innerHTML, that opens the door to XSS attacks. Stick to innerText or textContent for anything that comes from users.

Pitfall: the element is not found

If querySelector() matches nothing, it returns null, and the next line throws:

const total = document.querySelector('#totals') //typo, returns null
total.innerText = '$45.99' //TypeError: Cannot set properties of null

Check the selector for typos first. If the selector is right, your script probably ran before the element existed. Load the script with the defer attribute, or place the <script> tag at the end of the <body>, so the DOM is ready when your code runs.

Form fields are different

For <input> and <textarea> elements, the text lives in the value property, not in innerText:

document.querySelector('#email').value = '[email protected]'

Setting innerText on an input does nothing useful, and it’s a common source of confusion.

~~~

Related posts about platform: