The Document Object Model (DOM)

The Document Object Model

Using the DOM in JavaScript

The structure of a web page

The Document Object Model (DOM) is like a map or blueprint of a web page. It helps us understand the structure and content of an HTML document. Think of it as a way to interact with and manipulate the elements on a web page using JavaScript.

Imagine a web page as a tree, with the root element being the HTML tag. Each element on the page, such as headings, paragraphs, images, and buttons, is like a branch or node on the tree.

The DOM allows us to access these elements and perform various actions on them. We can change the text inside a paragraph, add or remove elements dynamically, apply styles to make things look pretty, and even respond to user interactions like button clicks.

JavaScript provides us with tools, such as the getElementById() method, to select specific elements based on their unique identifier, known as the "id" attribute. We can also use other methods like querySelector() to select elements based on CSS-like patterns.

By understanding the DOM, we can write JavaScript code to make web pages interactive, dynamic, and fun to use. It's like having a superpower to control the elements on a web page!

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a web page and provides methods and properties to interact with and manipulate the elements on the page using JavaScript.

Accessing HTML Elements through JavaScript

Accessing HTML elements through JavaScript is a fundamental concept in web development. It allows us to interact with and manipulate the content of a web page dynamically.

To use the DOM in JavaScript, follow these steps:

  1. Access the document object using the document keyword.
  2. Use various DOM methods and properties to interact with the elements on the page.
  3. Perform actions such as creating, modifying, or deleting elements.

Using getElementById()

To access a specific element by its id attribute, we can use the getElementById() method:

var element = document.getElementById('myElement');

This method retrieves the element with the specified id attribute value and assigns it to a variable for further manipulation.

Using querySelector()

We can also use the querySelector() method to access elements based on CSS selectors:

var element = document.querySelector('.myClass');

This method selects the first element that matches the specified CSS selector, such as a class name, and assigns it to a variable.

Using querySelectorAll()

If we want to select multiple elements that match a CSS selector, we can use the querySelectorAll() method:

var elements = document.querySelectorAll('.myClass');

This method returns a NodeList containing all elements that match the specified CSS selector.

Once we have accessed an element or a collection of elements, we can modify their properties, apply styles, or add event listeners to create interactive web experiences.

Remember to use the appropriate method based on your specific needs and CSS selector requirements. Understanding how to access HTML elements through JavaScript is a crucial skill for web development.

Some common DOM methods and properties

getElementById()
Description: Retrieves an element by its unique ID from the DOM.
Example: var element = document.getElementById('myElement');
Learn More: MDN - getElementById()
getElementsByClassName()
Description: Retrieves a collection of elements by their class name from the DOM.
Example: var elements = document.getElementsByClassName('myClass');
Learn More: MDN - getElementsByClassName()
getElementsByTagName()
Description: Retrieves a collection of elements by their tag name from the DOM.
Example: var elements = document.getElementsByTagName('div');
Learn More: MDN - getElementsByTagName()
querySelector()
Description: Retrieves the first element that matches a specified CSS selector from the DOM.
Example: var element = document.querySelector('#myElement .myClass');
Learn More: MDN - querySelector()
querySelectorAll()
Description: Retrieves a collection of elements that match a specified CSS selector from the DOM.
Example: var elements = document.querySelectorAll('div.myClass');
Learn More: MDN - querySelectorAll()
createElement()
Description: Creates a new element with the specified tag name.
Example: var newElement = document.createElement('div');
Learn More: MDN - createElement()
appendChild()
Description: Appends a child element to a parent element in the DOM.
Example: parentElement.appendChild(childElement);
Learn More: MDN - appendChild()
removeChild()
Description: Removes a child element from its parent element in the DOM.
Example: parentElement.removeChild(childElement);
Learn More: MDN - removeChild()
setAttribute()
Description: Sets the value of an attribute on an element in the DOM.
Example: element.setAttribute('class', 'myClass');
Learn More: MDN - setAttribute()
getAttribute()
Description: Retrieves the value of an attribute from an element in the DOM.
Example: var value = element.getAttribute('class');
Learn More: MDN - getAttribute()
classList
Description: Provides methods to manipulate the class names of an element in the DOM.
Example: element.classList.add('myClass'); element.classList.remove('otherClass'); element.classList.toggle('active');
Learn More: MDN - classList
addEventListener()
Description: Adds an event listener to an element, specifying the event type and a callback function to execute when the event occurs.
Example: element.addEventListener('click', handleClick);
Learn More: MDN - addEventListener()
innerHTML
Description: Gets or sets the HTML content of an element.
Example: var html = element.innerHTML;
element.innerHTML = '
Hello, World!
';
Learn More: MDN - innerHTML
style
Description: Provides access to the CSS properties of an element for styling purposes.
Example: element.style.color = 'red'; element.style.backgroundColor = 'blue';
Learn More: MDN - style
setAttribute()
Description: Sets the value of an attribute on an element.
Example: element.setAttribute('class', 'myClass'); element.setAttribute('data-id', '123');
Learn More: MDN - setAttribute()

HTML attributes

To access an attribute using the DOM in JavaScript, you can use the getAttribute() method. This method allows you to retrieve the value of a specific attribute from an element on a web page.

For example, let's say you have an HTML element with the attribute data-name set to "John". You can access this attribute using the following code:

var element = document.getElementById('myElement'); // Get the element by its ID var name = element.getAttribute('data-name'); // Retrieve the value of the 'data-name' attribute

In the code snippet above, getElementById() is used to get a reference to the HTML element with the ID "myElement". Then, getAttribute() is called on that element, passing in the attribute name "data-name". The value of the attribute is stored in the name variable.

Once you have accessed the attribute value, you can use it for various purposes in your JavaScript code, such as displaying it on the page, performing calculations, or using it in conditional statements.

It's important to note that attribute names are case-sensitive, so make sure to use the exact name of the attribute as it appears in your HTML.

By using the getAttribute() method, you can retrieve attribute values and incorporate them into your JavaScript logic to create dynamic and interactive web experiences.

Dynamic and interactive web pages

Using the DOM, you can create dynamic and interactive web pages. You can manipulate the content, style, and behavior of elements, respond to user actions, and create dynamic effects.

DOM in practise

Creating a Pop-Up Window with JavaScript and DOM Manipulation

Creating a pop-up window on a web page can be achieved using JavaScript and DOM manipulation. Here's a step-by-step guide on how to create a pop-up window that appears when a button is clicked and disappears when clicked again:

  1. Start by adding a button element to your HTML code. Give it a unique id to identify it in JavaScript. <button id="popupButton">Open Pop-Up</button>
  2. Next, define a JavaScript function that will be triggered when the button is clicked. Inside the function, use DOM manipulation to create a new HTML element representing the pop-up window, such as a div . function createPopUp() { const popUp = document.createElement('div'); // Customize the pop-up window using CSS styles // ... }
  3. Customize the appearance of the pop-up window using CSS styles. There are two options:
    • Option 1: Set the individual style properties of the pop-up window element using JavaScript. For example: popUp.style.position = 'fixed'; popUp.style.top = '50%'; popUp.style.left = '50%'; popUp.style.transform = 'translate(-50%, -50%)'; // ...
    • Option 2: Assign an existing CSS class to the pop-up window element. This class can be defined in a separate CSS file or within a <style> block in your HTML. For example: popUp.classList.add('popup-window'); // ...
  4. Append the pop-up window element to the document body using DOM manipulation methods, such as appendChild or insertBefore . document.body.appendChild(popUp);
  5. Finally, add an event listener to the pop-up window element to detect when it is clicked. Inside the event handler, use DOM manipulation to remove the pop-up window from the document, effectively closing it. popUp.addEventListener('click', function() { document.body.removeChild(popUp); });

By following these steps, you can create a pop-up window that appears on the page when a button is clicked and disappears when clicked again. This technique allows you to display additional information or interactive elements without permanently altering the page layout.