Skip to content
On this page

Updating the DOM

Once you have selected a DOM node, you can easily update it using various methods. Here are the primary techniques:

Modifying Text Content

  1. Using innerHTML: This allows you to set HTML content, which can modify the node's text and structure:

    javascript
    let p = document.getElementById('p-id');
    p.innerHTML = 'ABC'; // Changes text to ABC
    p.innerHTML = 'ABC <span style="color:red">RED</span>'; // Updates HTML structure

    Be cautious with innerHTML to avoid XSS attacks, especially with dynamic content.

  2. Using innerText or textContent: These methods set plain text, automatically encoding any HTML:

    javascript
    let p = document.getElementById('p-id');
    p.innerText = '<script>alert("Hi")</script>'; // This will be encoded

    Note: innerText does not return hidden text, while textContent does. IE<9 does not support textContent.

Modifying CSS Styles

You can change the styles of a DOM node using the style property, using camelCase for CSS properties:

javascript
let p = document.getElementById('p-id');
p.style.color = '#ff0000'; // Changes text color
p.style.fontSize = '20px'; // Sets font size
p.style.paddingTop = '2em'; // Adds padding

Example Exercise

Given the following HTML structure:

html
<div id="test-div">
  <p id="test-js">javascript</p>
  <p>Java</p>
</div>

You can modify the <p> element with ID test-js as follows:

javascript
// Select the <p>javascript</p> node
let js = document.getElementById('test-js');

// Change the text to 'JavaScript'
js.innerText = 'JavaScript';

// Change CSS styles: color to red and font-weight to bold
js.style.color = '#ff0000';
js.style.fontWeight = 'bold';

// Test cases
if (js && js.parentNode && js.parentNode.id === 'test-div' && js.id === 'test-js') {
    if (js.innerText === 'JavaScript') {
        if (js.style && js.style.fontWeight === 'bold' && (js.style.color === 'red' || js.style.color === '#ff0000' || js.style.color === '#f00' || js.style.color === 'rgb(255, 0, 0)')) {
            console.log('test passed!');
        } else {
            console.log('css style test failed!');
        }
    } else {
        console.log('text test failed!');
    }
} else {
    console.log('node test failed!');
}

This demonstrates how to effectively update text and styles in the DOM.

Updating the DOM has loaded