64. What is the Document Object Model (DOM) in JavaScript?
medium

The Document Object Model (DOM) is an API for HTML and XML documents. In other words, it's a way of accessing and manipulating the elements and attributes of a web page using JavaScript.


Here are some examples:


1. Finding all the links on a page:

const links = document.querySelectorAll('a');
for (let i = 0; i < links.length; i++) {
  console.log(links[i].href);
}

2. Changing the text of an element:

const heading = document.querySelector('h1');
heading.textContent = 'New Heading';

3. Adding a new element to the page:

const newElement = document.createElement('div');
newElement.innerHTML = '<p>Hello, world!</p>';
document.body.appendChild(newElement);

4. Removing an element from the page:

const elementToRemove = document.querySelector('.example-class');
elementToRemove.remove();

These are just a few examples of what you can do with the DOM in JavaScript. It's a powerful tool for building dynamic and interactive web applications.