Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Html in JavaScript

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 DOM

or

const newDiv = document.createElement("div");newDiv.innerHTML = "<h1>Replaced Content</h1>";oldElement.replaceWith(newDiv);  // Replace old element with new one

Summary

Property/MethodPurpose
innerHTMLGet/set HTML inside an element
outerHTMLGet/set entire element’s HTML
textContentGet/set only text content
createElementCreate a new HTML element
appendChildAdd 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?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql