JavaScript: Access HTML DOM (Document Object Model)

DOM (Document Object Model) is a standard allows to dynamically access the HTML documents, its styles, content and structure. It also allows dynamically update the content.

JavaScript is a dynamically typed, object-based scripting language that runs in a host environment, usually a web-browser. But it also used for server-side programming. JavaScript supports HTML DOM; so that we can use JavaScript to write DOM based programs.

Lets take a simple HTML page and check how we can access DOM through JavaScript:

Save this below code into “sample.html” and open it in web-browser.

<html>
    <head>
        <title>Sample HTML DOM</title>
    </head>

    <body>
        <h1 id="msg">
            Sample HTML DOM - Test Page
        </h1>

        <button type="button" onclick="ChangeText()">Test</button>

        <script>
            function ChangeText() {
                ele = document.getElementById("msg");
                ele.innerHTML = "Hello, HTML DOM!";
            }
        </script>
    </body>
</html>

Its a simple web-page displays “Sample HTML DOM – Test Page” message. We have written a simple JavaScript code, which runs when we click on “Test” button.

Look at the JavaScript code, we are accessing an HTML element through HTML document object. We need <h1> element here; so we get this element by using getElementById based on its ID. Once we get the element, we can change it text by setting its innerHTML attribute.

Once you click on “Test” button from this web-page; our code changes the text to “Hello, HTML DOM!” message.

..

Leave a Reply