DEV Community

Narmatha
Narmatha

Posted on

DOM IN JAVASCRIPT

WHAT IS DOM IN JAVASCRIPT?

DOM stands for Document Object Model.

The DOM is a programming representation of an HTML page. JavaScript uses the DOM to access, change, add, or remove HTML elements and their content/styles.

The browser converts this HTML into a DOM tree:

Document

└── html

├── h1
│ └── "Hello World"

└── button
└── "Click Me"

JavaScript can access these elements through the DOM.

Why Do We Need DOM?

Without the DOM, JavaScript would not have an easy way to interact with the HTML page.

We use the DOM to:

*Change HTML content
*Change CSS/styles
*Change attributes
*Add new elements
*Remove elements
*Handle button clicks
*Handle user input
*Create dynamic webpages
*Respond to user actions

For example, when you click a button and something changes on the webpage, JavaScript is usually interacting with the DOM.

Methods of DOM in JavaScript

DOM methods are functions provided by the browser to find, create, modify, and remove HTML elements.

1. Finding Elements

getElementById()

Finds an element using its id.

`let heading = document.getElementById("title");

console.log(heading);
`

getElementsByClassName()

Finds elements using their class name.

`

Hello

Welcome

`

`let elements = document.getElementsByClassName("text");

console.log(elements);
`

getElementsByTagName()

Finds elements using their HTML tag.

`let paragraphs = document.getElementsByTagName("p");

console.log(paragraphs);`

querySelector()

Finds the first matching element using a CSS selector.

let heading = document.querySelector("#title");

Class:

`let element = document.querySelector(".text");

`Tag:

let paragraph = document.querySelector("p");

Top comments (0)