Building on our knowledge from Chapter 8, this chapter covers the core techniques for dynamically changing a webpage. This is where you bring your static HTML/CSS structure to life by modifying content, attributes, and styling based on user interaction or application logic.
Modifying Element Content
You have two primary ways to change the content of an element:
textContent
: Gets or sets the text content of an element and its descendants. It strips out all HTML tags. Use this for security and performance when you only need to insert plain text.
JavaScript
const heading = document.querySelector('h1');
heading.textContent = 'New Title Set by JavaScript!';
innerHTML
: Gets or sets the content as raw HTML. This is powerful but must be used with caution, as inserting user-provided HTML can introduce Cross-Site Scripting (XSS) vulnerabilities.
JavaScript
const container = document.getElementById('output');
container.innerHTML = '<h2>This is a new subheading</h2><p>and some **bold** text.</p>';
Managing Attributes
Attributes (like src
, href
, or id
) are managed using a set of specific methods:
element.getAttribute('attrName')
: Gets the current value of an attribute.
element.setAttribute('attrName', 'newValue')
: Sets or changes an attribute's value.
element.removeAttribute('attrName')
: Removes an attribute entirely.
JavaScript
const image = document.querySelector('img');
// Change the image source
image.setAttribute('src', 'new-image.jpg');
// Check if a class attribute exists
const hasClass = image.hasAttribute('class');
Styling Elements (CSS)
There are two methods for changing the visual appearance of an element:
1. Direct Inline Styles (Avoid for complex styles)
You can access and change individual CSS properties using the .style
property, using camelCase for multi-word properties (e.g., backgroundColor
).
JavaScript
const box = document.getElementById('box');
box.style.backgroundColor = 'blue';
box.style.fontSize = '24px';
This applies inline styles directly to the element, which often makes maintenance difficult.
2. Managing CSS Classes (Best Practice)
The best way to control styling is to pre-define styles in your CSS file and then use JavaScript to add or remove class names from the element. The classList
property provides handy methods for this:
element.classList.add('className')
: Adds a class.
element.classList.remove('className')
: Removes a class.
element.classList.toggle('className')
: Adds the class if it's not present, and removes it if it is (perfect for toggling menus!).
element.classList.contains('className')
: Checks if a class is present (returns true/false).
JavaScript
const button = document.querySelector('.toggle-btn');
// Toggle the 'active' class on click (see next chapter for event listeners)
button.classList.toggle('active');
Creating and Deleting Elements
You can create entirely new HTML elements and insert them into the DOM:
Creation: document.createElement('tagName')
Text: Set the textContent
or innerHTML
.
Insertion
JavaScript
// 1. Create a new <li> element
const newItem = document.createElement('li');
// 2. Add content and a class
newItem.textContent = 'Chapter 9 Completed!';
newItem.classList.add('finished-item');
// 3. Find the parent <ul> and append the new item
const list = document.querySelector('ul');
list.appendChild(newItem);
// Removing an element
const oldItem = document.getElementById('item-to-remove');
if (oldItem) {
oldItem.remove(); // The modern and simplest way to remove an element
}
By mastering these manipulation techniques, you gain the ability to build dynamic user interfaces that respond instantly to application changes.