DEV Community

Ehab Hussein
Ehab Hussein

Posted on

DOM (part 1)

DOM stands for Document Object Model, which is a web API provided by the web browser for the JavaScript engine in order to style and access the HTML elements from Javascript code
as a conceptual model, it is represented as a tree structure due to its hierarchical nature.

Image description

The browser converts this to the below tree structure:

Image description

as you can see the document object is leading the tree, actually it isn't the root of the tree but all tree nodes inherit the base functionalities from it. such as addEventListener which is an inherited function for every HTML element in our tree that allows you to add event to occur on any HTML element you want.
ex:

document.body.addEventListener('click', function() {
        // Change the body's background color to yellow
        this.style.backgroundColor = 'yellow';
Enter fullscreen mode Exit fullscreen mode

the real root here is the HTML object since it is the root element of any HTML file. all children branches branch from it forming the tree structure so it can accessed and manipulated easily

as example if you want to access the root element which is HTML tag

document.documentElement

access body element:

document.body

Accessing Body Elements:
To access elements within the <body> of an HTML document, the document object provides various methods and properties. One commonly used method is getElementById(), which allows you to retrieve an element by its unique ID attribute. For example:

var myElement = document.getElementById('myElementId');

This retrieves the element with the ID "myElementId" from the document's DOM tree.

Additionally, you can use methods like getElementsByClassName(), getElementsByTagName(), and querySelector() to access elements based on their class names, tag names, or CSS selectors, respectively.

Top comments (0)