Understanding DOM

DOM

It refers to Document Object Model. It represent the logical structure of the page.

Accessing DOM

document keyword is an object. So as to get the html of the page we can write document.documentElement, to get the head document.head and to get the body docuyment.body.

There is one more object which is called the window object. If you write document or window.document it is one and the same thing as window also have a document property.

There is one more object called screen which has details about the screen like height, width etc.

console.log(window.location === document.location) => true

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page. The Document.location read-only property returns a Location object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL.

Fetching Elements

Let’s say if I want to change the color of the element being fetched.

Similarly we can fetch the elements using Tagname, className, CSS selector as well.

Using CSS selector here

Event Handling

I want that on clicking on the button I should get a message saying “Hello”

1st way

2nd way

Adding event listener. But for that we need to first fetch the element.

More than 1 event listener can also be added to the element.

Other Mouse Events and Keyboard Events

Let’s consider a div with some css and an input with some css.

Let’s talk about mouse over and mouse out

Now let’s talk about some keyboard events as well.

Let’s say you are building a game and the keypress in not just restricted to a input box. But that is available throughout the screen. In that case we would be doing a keypress over a document.

Please note that arrow keys, tab, shift, alt etc keys are not included in the keypress.

Keypress can be considered as pressing and releasing a key.

There are events like keydown and keyup as well which will mean pressing and releasing the key.

Keydown will take care of the alt, shift, tab etc keys.

So as to detect which key has been pressed follow the below steps:

Pressed A

Propagation of Event

Let’s understand this with help of an example.

On clicking the inner div, the event for inner div, outer div and document will be triggered. On clicking the outer div, event for outer div and document will be triggered. This is known as event propagation.

On clicking inner div
On clicking outer div

In order to stop event propagation, we need to handle it.

On clicking inner div

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts