DEV Community

Kiruthiga S
Kiruthiga S

Posted on

DOM(part-2)

What is DOM
The DOM (Document Object Model) in JavaScript is a programming interface that represents an HTML or XML document as a tree of objects. It allows JavaScript to access and manipulate the structure, content, and styles of a web page dynamically.

Why is DOM important

  • Access HTML elements.
  • Modify text and HTML content.
  • Change CSS styles.
  • Add or remove elements.
  • Handle user events (clicks, keyboard input, etc.).
  • Create interactive and dynamic web pages.

When do we use DOM
We use the DOM whenever we want JavaScript to read, change, add, remove, or respond to elements on a web page.
The DOM (Document Object Model) is created by the browser, not by JavaScript.

<!DOCTYPE html>
<html>

<body>
    <h1 id="heading-1">Hello</h1>
    <h1 id="heading-2">Hi</h1>
    <h1 id="heading-3">Hlo</h1>

    <button onclick="changeText()">Change Update</button>

    <script>
        function changeText() {

            const element = document.getElementById("heading-1");
            console.log(typeof element);
            console.log(element.innerText);

            if (element.innerText == "Hello") {
                element.innerText = "Hi";
            } else {
                element.innerText = "Hello";
            }

        }
    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<body>

<button id="btn" onclick="button()">ON</button>

<script>
function button() {
    const element = document.getElementById("btn");

    console.log(typeof element);
    console.log(element.innerText);

    if (element.innerText == "ON") {
        element.innerText = "OFF";
    } else {
        element.innerText = "ON";
    }
}
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)