CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

JavaScript – Access HTML DOM (Document Object Model)

DOM (Document Object Model) is a standard, allows to dynamically access the HTML documents, it’s 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.

Let’s 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>

It’s 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 it’s ID. Once we get the element, we can change it’s 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.

..

JavaScript – Access HTML DOM (Document Object Model)

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top