Dom Html in JavaScript
? DOM HTML in JavaScript
What is DOM HTML?
The DOM (Document Object Model) represents the entire HTML document as a tree of objects.
DOM HTML refers to the manipulation of the HTML content using JavaScript via the DOM.
You can read, change, add, or remove HTML elements and content dynamically.
Accessing and Modifying HTML Content
1. innerHTML
Gets or sets the HTML content inside an element.
<div id="content"> <p>Hello, World!</p></div><script>const contentDiv = document.getElementById("content");console.log(contentDiv.innerHTML); // "<p>Hello, World!</p>"contentDiv.innerHTML = "<h2>New Heading</h2><p>Updated content</p>";</script>2. outerHTML
Gets or sets the entire HTML of the element itself, including the element tags.
const contentDiv = document.getElementById("content");console.log(contentDiv.outerHTML); // "<div id='content'>...</div>"contentDiv.outerHTML = "<section id='content'>New Section Content</section>";3. textContent
Gets or sets the text content inside an element (ignores HTML tags).
const contentDiv = document.getElementById("content");console.log(contentDiv.textContent); // "Hello, World!"contentDiv.textContent = "Just plain text now";Adding New HTML Elements
Use createElement and appendChild:
const newPara = document.createElement("p");newPara.innerHTML = "This is a new paragraph.";document.body.appendChild(newPara);Removing or Replacing Elements
const oldElement = document.getElementById("content");oldElement.remove(); // Remove the element from DOMor
const newDiv = document.createElement("div");newDiv.innerHTML = "<h1>Replaced Content</h1>";oldElement.replaceWith(newDiv); // Replace old element with new oneSummary
| Property/Method | Purpose |
|---|---|
innerHTML | Get/set HTML inside an element |
outerHTML | Get/set entire element’s HTML |
textContent | Get/set only text content |
createElement | Create a new HTML element |
appendChild | Add a new element as a child |
remove() | Remove an element |
replaceWith() | Replace an element with another |
Would you like me to show how to safely insert HTML to avoid XSS, or how to traverse and modify HTML nodes?