DEV Community

Lokesh
Lokesh

Posted on

DOM in JavaScript for Beginners

What Is DOM?

DOM stands for Document Object Model. It allows JavaScript to access and change HTML elements on a webpage.

Using the DOM, we can change text, add new elements, delete elements, change styles, and respond to button clicks.

1. Accessing Elements

We can use getElementById() to select an HTML element using its ID.

<h1 id="title">Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode
let heading = document.getElementById("title");

console.log(heading);
Enter fullscreen mode Exit fullscreen mode

Here, JavaScript selects the heading whose ID is title.

2. Updating Elements

We can use textContent to change the text of an element.

heading.textContent = "Welcome to JavaScript!";
Enter fullscreen mode Exit fullscreen mode

Now, the heading displays the new text.

We can also change its style:

heading.style.color = "blue";
Enter fullscreen mode Exit fullscreen mode

This changes the heading's text color to blue.

3. Creating Elements

We can create new HTML elements using createElement().

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

paragraph.textContent = "This is a new paragraph.";

document.body.appendChild(paragraph);
Enter fullscreen mode Exit fullscreen mode

Here, JavaScript creates a paragraph, adds text to it, and places it inside the webpage's body.

4. Deleting Elements

We can remove an HTML element using the remove() method.

<p id="message">Hello World!</p>
Enter fullscreen mode Exit fullscreen mode
let paragraph = document.getElementById("message");

paragraph.remove();
Enter fullscreen mode Exit fullscreen mode

The paragraph will be removed from the webpage.

Important DOM Methods and Properties

  • getElementById() — selects an element by ID.
  • querySelector() — selects the first matching element.
  • textContent — changes or reads text.
  • createElement() — creates a new element.
  • appendChild() — adds an element inside another element.
  • remove() — removes an element.
  • addEventListener() — responds to user actions.

Top comments (0)