DEV Community

Cover image for Introduction to DOM - JavaScript
Dhanush P
Dhanush P

Posted on

Introduction to DOM - JavaScript

Introduction to DOM:

  • The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document, such as the HTML representing a web page.
  • The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects.
  • DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.
  • Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.

What is Document?

  • A web page is a document that can be either displayed in the browser window or as the HTML source.
  • In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated.
  • As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.

What is a DOM tree?

  • A DOM tree is a tree structure whose nodes represent an HTML or XML document's contents. Each HTML or XML document has a DOM tree representation. For example, consider the following document:
<html lang="en">
  <head>
    <title>My Document</title>
  </head>
  <body>
    <h1>Header</h1>
    <p>Paragraph</p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

It has a DOM tree that looks like this:

https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/vpd78awctmdjmla75fpl.jpg

JavaScript getElementById() Method

The getElementById() method of the document object returns an HTML element with the specified id.

Here’s the syntax of the getElementById() method:

const element = document.getElementById(id);
Enter fullscreen mode Exit fullscreen mode

In this syntax:

`id` is a string that represents the id of the element to select.
Enter fullscreen mode Exit fullscreen mode

Note that the method matches ID case-sensitively. For example, the 'root' and 'Root' are different.

If the document has no element with the specified id, the getElementById() method returns null.

JavaScript getElementById() method example

Suppose you have a document with two p elements:

<p id="first">Hi, There!</p>
<p>JavaScript is fun.</p>
Enter fullscreen mode Exit fullscreen mode

The following code shows how to get the element with the id first:

const elem = document.getElementById("first");
Enter fullscreen mode Exit fullscreen mode

See the following demo:

https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/zn29x1mze8w8cshhgte4.png

References:

https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
https://www.javascripttutorial.net/javascript-dom/

Top comments (0)