Sitemap

Java script Day 2-Working with the Document Object Model (DOM) in JavaScript

2 min readFeb 23, 2023

--

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of an HTML or XML document as a tree-like model where each node in the tree represents an element or attribute in the document. In this article, we’ll explore how to manipulate the DOM using JavaScript.

Get Jagadeesh Gade’s stories in your inbox

Join Medium for free to get updates from this writer.

Accessing DOM Elements: To access a DOM element in JavaScript, you can use the ‘getElementById’, ‘getElementsByClassName’, or ‘getElementsByTagName’ methods. These methods return a reference to the element that matches the specified criteria.

// accessing an element by id
let heading = document.getElementById("heading");
// accessing elements by class name
let paragraphs = document.getElementsByClassName("paragraph");
// accessing elements by tag name
let images = document.getElementsByTagName("img");

Manipulating DOM Elements: Once you have a reference to a DOM element, you can manipulate its properties, such as its text content, attributes, or style.

// changing the text content of an element
heading.textContent = "New Heading";
// changing the background color of an element
heading.style.backgroundColor = "blue";
// adding a new attribute to an element
heading.setAttribute("class", "large-heading");

Creating New DOM Elements: You can also create new DOM elements dynamically using JavaScript. To create a new element, you can use the ‘createElement’ method, and to add the element to the DOM, you can use the ‘appendChild’ method.

// creating a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
// adding the new paragraph to the DOM
document.body.appendChild(newParagraph);

Handling Events: JavaScript allows you to add event listeners to DOM elements, which trigger a function when a specific event occurs, such as a click or hover event.

// adding a click event listener to a button
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});

In conclusion, the DOM is a powerful feature of JavaScript that allows you to manipulate the structure and content of web documents dynamically. By mastering the concepts and techniques covered in this article, you can create interactive and dynamic web pages using JavaScript.

--

--

Jagadeesh Gade
Jagadeesh Gade

Written by Jagadeesh Gade

SDE 2 with expertise in HTML, CSS, JS, Node.js, React, Express.js, and MongoDB.Passionate about creating efficient,and scalable web applications.