DOM HTML

The DOM allows JavaScript to dynamically manipulate HTML content, enabling updates to text, attributes, and element structure on a webpage. This is achieved using properties like innerHTML, outerHTML, and methods like setAttribute.

Key Topics

Using innerHTML

The innerHTML property allows you to get or set the HTML content inside an element.

const element = document.getElementById("demo");
element.innerHTML = "Updated Content";

Output

Updated Content

Explanation: The innerHTML property replaces the content of the element with id "demo" with new HTML content.

Using outerHTML

The outerHTML property allows you to get or set the entire HTML of an element, including the element itself.

const element = document.getElementById("demo");
element.outerHTML = "
Replaced Element
";

Output

(The original element is replaced with new content.)

Explanation: The outerHTML property replaces the entire element, including its tags and content, with new HTML.

Updating Attributes

Attributes of HTML elements can be updated dynamically using methods like setAttribute or properties like src and href.

const link = document.getElementById("link");
link.setAttribute("href", "https://example.com");
link.textContent = "Visit Example";

Output

(The link's href is updated to "https://example.com" and its text displays "Visit Example".)

Explanation: The setAttribute method dynamically updates the href attribute, and the textContent property updates the displayed text.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating HTML manipulation using JavaScript.

<!DOCTYPE html>
<html>
    <head>
        <title>DOM HTML Example</title>
    </head>
    <body>
        <div id="demo">Original Content</div>
        <button onclick="updateContent()">Update Content</button>

        <script>
            function updateContent() {
                const element = document.getElementById("demo");
                element.innerHTML = "Updated Content";
            }
        </script>
    </body>
</html>

Key Takeaways

  • innerHTML: Use to get or set the content inside an element.
  • outerHTML: Use to get or replace the entire element, including its tags.
  • Dynamic Attributes: Update attributes like href or src dynamically.
  • DOM Integration: Leverage these properties to manipulate the HTML structure for interactive applications.