Week 9: Interacting with Web Pages - The DOM
Learn how JavaScript breathes life into HTML documents using the Document Object Model.
Explore Chapter 9Manipulating Element Content and Style.
Once you have selected an element object, you can change its content, attributes, and appearance.
Changing Content:
- textContent: Gets or sets the text content of an element and all its descendants, ignoring any HTML tags within. It's often safer for setting plain text.
// Assuming: <p id="myPara">Initial <em>text</em></p> let para = document.getElementById("myPara"); console.log(para.textContent); // "Initial text" (ignores <em>) para.textContent = "New text content set via JS."; // Now HTML is: <p id="myPara">New text content set via JS.</p> - innerHTML: Gets or sets the HTML content (including tags) within an element. Use with caution when setting content from untrusted sources, as it can introduce security risks (Cross-Site Scripting - XSS).
// Assuming: <div id="myDiv"></div> let div = document.getElementById("myDiv"); div.innerHTML = "<strong>Bold text</strong> and a <a href='#'>link</a>."; // The div now contains the actual bold text and link elements.
Changing Attributes:
- You can often access common attributes directly as properties of the element object (e.g., id, className, src, href).
- Use getAttribute(name) and setAttribute(name, value) for any attribute.
<img id="myImage" src="old.jpg" alt="Old Image">
<a id="myLink" href="/old-page">Old Link</a>
<script>
let img = document.getElementById("myImage");
let link = document.getElementById("myLink");
// Using direct properties
img.src = "new.png";
img.alt = "New Image";
link.href = "/new-page";
// Using setAttribute
link.setAttribute("target", "_blank"); // Add target="_blank" attribute
</script>
Changing CSS Styles:
You can modify inline CSS styles using the style property of the element object. CSS property names are converted to camelCase (e.g., background-color becomes backgroundColor).
// Assuming: <p id="styledPara">Style me!</p>
let styledP = document.getElementById("styledPara");
styledP.style.color = "blue";
styledP.style.backgroundColor = "#f0f0f0"; // Note camelCase
styledP.style.fontSize = "20px";
styledP.style.padding = "10px";
For more complex styling changes, it's usually better to add or remove CSS classes using the classList property (element.classList.add('newClass'), element.classList.remove('oldClass'), element.classList.toggle('activeClass')).