Open In App

How are DOM utilized in JavaScript ?

What is DOM

The document object Model (DOM) represents the full HTML document. When an HTML document is loaded within the browser, it becomes a document object. The root element represents the HTML document, its properties, and its methods. With the assistance of a document object, we will add dynamic content to our web page. 



In another word, the way a document’s content is accessed and modified is the Document Object Model or DOM. The objects are organized in a hierarchy. Web document objects are applied in this hierarchical data structure.

DOM and JavaScript



The DOM is not a programming language, but without it, the JavaScript language wouldn’t have any model or notion of websites, HTML documents, SVG documents, and their parts. The document as an entire, the head, tables within the document, table headers, text within the table cells, and every other element in a document is part of the document object model for that document. They will all be accessed and manipulated using the DOM and a scripting language like JavaScript.

Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes, change the prevailing elements and attributes and even remove existing elements and attributes. JavaScript also can react to existing events and create new events on the page.

Example 1: The getElementById() using id is used to access elements and attributes. The innerHTML is used to access the content of an element.




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM by javascript</title>
</head>
 
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h1 id="one">using Javascript</h1>
    <p>This is the welcome message.</p>
    <script type="text/javascript">
        var text = document.getElementById("one").innerHTML;
        console.log("The first heading is " + text);
    </script>
</body>
 
</html>

Output:

 

Example 2: The getElementsByTagName() method will return an array of all the items with the same tag name. Elements and attributes are accessed using the tag name.




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM using javascript</title>
</head>
 
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h1>Welcome</h1>
    <p>Hi GeeksforGeeks Welcomes you</p>
    <h2>GFG</h2>
    <p id="second">A computer science portal</p>
    <script type="text/javascript">
        var paragraphs = document.getElementsByTagName("p");
                console.log("Content in the second paragraph is "                 
                            + paragraphs[1].innerHTML);
                document.getElementById("second").innerHTML =
                        "The original message is changed.";
    </script>
</body>
 
</html>

Output:

 


Article Tags :