Changing the Page
Now make things happen — change text, styles, classes and attributes with JavaScript.
What you will learn
- Change content with textContent and innerHTML
- Change styles and classes
- Create and add new elements
Change content
The simplest change is swapping an element’s text. Click the button below to see it happen.
<p id="out">Old text</p>
<button onclick="document.getElementById('out').textContent = 'New text! ✨'">
Change it
</button>When clicked, the button finds the paragraph with id="out" and sets its .textContent to a new string. The old words are instantly replaced by the new ones — no reload.
Note: Output: Before click: Old text After click: New text! ✨
Change style and classes
JavaScript can also restyle elements live by setting their .style properties — the same things you set in CSS.
<p id="box" style="padding:12px">Watch my colour change</p>
<button onclick="
const b = document.getElementById('box');
b.style.background = '#4338ca';
b.style.color = 'white';
">Style me</button>On click we grab the paragraph into b, then set b.style.background to a purple colour and b.style.color to white. Each line is just like writing a CSS rule, but from JavaScript and applied immediately.
Note: Output: The paragraph’s background turns purple and its text turns white the moment you click.
Build new elements
You can even create brand-new elements from scratch and add them to the page. Click "Add item" repeatedly to grow the list.
<ul id="list"></ul>
<button onclick="
const li = document.createElement('li');
li.textContent = 'New item ' + (document.getElementById('list').children.length + 1);
document.getElementById('list').appendChild(li);
">Add item</button>document.createElement('li') makes a fresh <li> in memory (not on the page yet). We give it text — the number is just how many items the list already has, plus one. Then appendChild(li) actually drops it into the <ul>, so each click adds the next item.
Creating and adding an element is always the same three-step process:
- Create the element in memory:
document.createElement('li')makes a new<li>that is not on the page yet. - Fill it with content:
li.textContent = ...sets the text the element will show. - Append it to the page:
appendChild(li)places the finished element inside its parent (<ul>), so it finally appears.
Note: Output: Click once → New item 1 Click again → New item 2 Click again → New item 3
Watch out: textContent inserts plain text safely. innerHTML inserts HTML — powerful, but never put untrusted user input into innerHTML (it is a security risk). Prefer textContent unless you specifically need HTML.
Q. Which safely changes the plain text of an element?
✍️ Practice
- Make a button that changes a heading’s text and colour.
- Make an “Add to list” button that appends a new
<li>each click.
🏠 Homework
- Build a colour-changer: buttons that change the page background to different colours.