DOM HTML
JavaScript HTML DOM: Changing HTML Content and Attributes
Section titled “JavaScript HTML DOM: Changing HTML Content and Attributes”The HTML DOM (Document Object Model) allows JavaScript to interact with and modify the content and structure of HTML elements dynamically.
Changing HTML Content with innerHTML and textContent
Section titled “Changing HTML Content with innerHTML and textContent”The most common way to change the content of an HTML element is by using its innerHTML or textContent properties.
element.innerHTML = newHTMLContent;
Section titled “element.innerHTML = newHTMLContent;”The innerHTML property gets or sets the HTML markup contained within an element. When setting innerHTML, the browser parses the provided string as HTML.
Example: Changing the content of a <p> element.
<!-- HTML --><p id="myParagraph">This is the original text.</p>
<script> const paragraph = document.getElementById("myParagraph"); if (paragraph) { paragraph.innerHTML = "**This is new, bold text!** And some <em>italic text</em>."; }</script>Security Warning: Be very careful when using innerHTML with content that comes from users or untrusted sources. If the content contains malicious scripts, it can lead to Cross-Site Scripting (XSS) vulnerabilities. Always sanitize user input before rendering it with innerHTML.
element.textContent = newTextContent;
Section titled “element.textContent = newTextContent;”The textContent property gets or sets the text content of an element and its descendants. It treats the provided string as plain text, so any HTML tags will be rendered as literal text, not parsed as HTML. This makes it safer for displaying user-provided text.
Example: Changing the content of an <h1> element safely.
<!-- HTML --><h1 id="mainHeader">Old Header</h1>
<script> const header = document.getElementById("mainHeader"); if (header) { // If this text came from a user, textContent is safer header.textContent = "New, Safe Header (even if it had <h1>tags</h1>)"; }</script>Explanation:
- The HTML document contains an element (e.g.,
<p id="myParagraph">or<h1 id="mainHeader">). - We use
document.getElementById()to get a reference to that element. - JavaScript then changes its
innerHTMLortextContentproperty.
Changing HTML Attribute Values
Section titled “Changing HTML Attribute Values”JavaScript can also change the values of HTML attributes.
Direct Property Access (for common attributes)
Section titled “Direct Property Access (for common attributes)”For many standard HTML attributes, you can access them directly as properties of the DOM element object.
`element.attributeName = newValue;`Example: Changing the src attribute of an <img> element and the href of an <a> element.
<!-- HTML --><img id="myImage" src="old-image.jpg" alt="An image"><a id="myLink" href="old-link.html">Old Link</a>
<script> const image = document.getElementById("myImage"); if (image) { image.src = "new-image.png"; image.alt = "A new, updated image"; }
const link = document.getElementById("myLink"); if (link) { link.href = "new-link.html"; link.target = "_blank"; // Add a new attribute }</script>setAttribute() and getAttribute()
Section titled “setAttribute() and getAttribute()”For any attribute (including custom data-* attributes or attributes whose names might conflict with element properties), it’s more robust to use setAttribute() and getAttribute().
`element.setAttribute('attributeName', 'newValue');``const currentValue = element.getAttribute('attributeName');`Example: Using setAttribute and getAttribute.
<!-- HTML --><div id="customDiv" data-info="initial info">Some content</div>
<script> const divElement = document.getElementById("customDiv"); if (divElement) { // Set a standard attribute divElement.setAttribute("class", "highlighted");
// Set a custom data attribute divElement.setAttribute("data-info", "updated information");
// Get an attribute value const currentInfo = divElement.getAttribute("data-info"); console.log("Current data-info:", currentInfo); // Output: updated information
// For data-* attributes, you can also use the `dataset` property: // divElement.dataset.info = "updated via dataset"; // console.log(divElement.dataset.info); }</script>Using document.write() (Caution!)
Section titled “Using document.write() (Caution!)”document.write(htmlString) writes directly to the HTML document stream. While it might seem like a simple way to add content, it has significant drawbacks:
- If used after the HTML document has finished loading,
document.write()will overwrite the entire document. This is usually undesirable. - It’s generally considered a legacy practice for most dynamic content generation.
- It can negatively impact performance and is harder to manage than targeted DOM manipulation.
Example (for demonstration, typically during initial page load):
<!DOCTYPE html><html><head> <title>Document.write Test</title></head><body> <h1>Content Before Write</h1> <script> // This is generally okay if used *while* the page is parsing, before it's fully loaded. document.write("<p>Content written by JavaScript at " + new Date() + "</p>"); </script> <p>Content After Write (if write doesn't overwrite everything)</p></body></html>
<!-- If you were to call document.write() from an event handler *after* the page loads, e.g., in a button click, it would erase the current page and replace it with the new content.-->Best Practice: Avoid document.write() for modifying content after the page loads. Use methods like innerHTML, textContent, appendChild(), or framework-specific techniques instead.
For further details on DOM manipulation, consult the MDN Web Docs on DOM.