Share


Javascript DOM Tutorial For Beginners


By gobrain

Jun 23rd, 2024

The Document Object Model (DOM) is fundamental for beginners learning JavaScript for web development because it bridges the gap between your code and the web page itself.

JavaScript brings web pages to life with interactivity, and DOM manipulation is the tool that makes it happen. Imagine you want a button to change color when clicked, or an image to swap when hovered over. You'll use DOM to target those elements and control their behavior.

In addition, by learning DOM, you understand how web pages are built and organized, making it easier to navigate and manipulate them with JavaScript.

Now, let's learn the basic principles of the DOM, its functionality, and how JavaScript interacts with it.

What is DOM?

DOM stands for Document Object Model. It is a tree-like structure that represents the HTML or XML documents we see in web browsers. It's like a blueprint or map of the webpage. Each element on the page, such as a paragraph, image, or button, is represented as a node in the tree and the document object is at the top of the hierarchy, representing the entire webpage.

DOM takes the HTML code of a web page and creates a tree-like structure in memory. This structure reflects the organization of the elements on the page.

Each element in the DOM tree becomes an object with properties and methods. You can use JavaScript code to access these objects, change their content, style, or even remove them from the page.

By manipulating the DOM with JavaScript, you can create dynamic web pages that update and respond to user actions. This is what makes buttons work, text change on hover, and animations appear.

How Javascript Interact with DOM

JavaScript interacts with the DOM through the DOM API (Application Programming Interface). This API provides a set of methods and properties that allow JavaScript code to access, manipulate, and create elements in the DOM tree.

Now let's look at closely the basic DOM API methods and properties.

How To Access Elements In DOM

The first step to manipulating the DOM is to access the elements on the webpage. There are several ways to access elements, including using:

  • getElementById(): allows you to access an element using its id attribute
  • getElementsByClassName(): allows you to access all elements with the same class name
  • getElementsByTagName(): allows you to access all elements with the same tag name
  • querySelector(): allows you to access an element using a CSS selector
// getElementById
const elementById = document.getElementById('myElement');
    
// getElementsByClassName
const elementsByClass = document.getElementsByClassName('myClass');
for (const el of elementsByClass) {
   // Codes here
}

// getElementsByTagName
const elementsByTag = document.getElementsByTagName('span');
for (const el of elementsByTag) {
   // Codes here
}

// querySelector
const selectedElement = document.querySelector('.myClass');

How To Modify Elements In DOM

Once you have accessed an element, you can manipulate its properties and attributes.To modify an element in the DOM, you can access its properties and attributes.

Changing HTML Content:

  • innerHTML Property: Change the HTML content of an element.
  • textContent Property: Modify the text content of an element.
// Changing HTML content
introParagraph.innerHTML = "New content with <em>emphasis</em>";

// Modifying text content
introParagraph.textContent = "Updated text content";

Changing Attributes:

  • getAttribute and setAttribute: Get or set the value of an attribute.
  • classList Property: Add, remove, or toggle classes of an element.
// Changing attributes
let link = document.querySelector("a");
link.setAttribute("href", "https://www.example.com");

// Adding and removing classes
mainContainer.classList.add("highlight");
mainContainer.classList.remove("lowlight");

Manipulating Styles

  • style Property: Access and modify inline styles of an element.
  • classList Property: Also useful for adding or removing classes for styling.
// Manipulating styles
mainContainer.style.backgroundColor = "lightblue";
introParagraph.style.fontSize = "18px";

// Using classList for styling
mainContainer.classList.add("highlight");

How To Add or Remove Elements In DOM

You can also easily add and remove elements in DOM using the following methods:

  • Adding: createElement() and appendChild()
  • Removing: remove()
const myDiv = document.getElementById('myDiv');
const newParagraph = document.createElement('p');
newParagraph.textContent = 'New paragraph';
myDiv.appendChild(newParagraph);
const myElement = document.getElementById('myElement');
myElement.remove();

Event listeners

Event listeners allow you to add functionality to elements when certain events occur, such as when the user clicks a button or scrolls the page. To add an event listener to an element, you can use the addEventListener() method.

const myButton = document.getElementById('myButton');
myButton.addEventListener('click', function() {
  console.log('Button clicked');
});

Common Event Types includes:

  • Mouse Events: Click, mouseover, mouseout, etc.
  • Keyboard Events: Keydown, keyup, keypress.
  • Form Events: Submit, reset, change.

DOM Navigation

DOM navigation refers to the process of navigating and manipulating the Document Object Model (DOM) in web development.

Traversing the DOM Tree:

  • parentNode, childNodes, firstChild, lastChild: Move between nodes.
  • nextSibling and previousSibling: Navigate to adjacent nodes.
// Traversing the DOM tree
let parentOfIntro = introParagraph.parentNode;
let firstChildOfMainContainer = mainContainer.firstChild;
let nextElement = introParagraph.nextSibling;

Node Properties:

Nodes in the Document Object Model (DOM) are represented by various types, such as elements, text nodes, attribute nodes, etc. Each type of node has different properties associated with it. Here are some common properties of DOM nodes:

  • nodeName, nodeType, nodeValue: Retrieve information about nodes.
// Retrieving node information
console.log(introParagraph.nodeName); // Output: "P"
console.log(introParagraph.nodeType); // Output: 1 (Element Node)

Best Practices When Working With DOM

When working with the Document Object Model (DOM) in JavaScript, following best practices can lead to more efficient and maintainable code. Here are some tips and best practices to consider:

  • Cache DOM Elements: Avoid repetitive DOM lookups by storing references to frequently accessed elements in variables. This reduces the number of times you query the DOM, improving performance.
  • Event Delegation: Attach event listeners to parent elements instead of individual child elements whenever possible. This reduces the number of listeners needed and improves efficiency, especially for dynamically added elements.
  • Batch DOM Updates: If you need to make multiple DOM changes, group them together whenever possible. This minimizes the number of times the browser needs to repaint the page, leading to smoother performance.
  • Use Modern Selectors: Prefer querySelector and querySelectorAll for element selection. They offer more flexibility and power compared to older methods like getElementById and getElementsByTagName.
  • Separate Concerns: Keep your JavaScript code separate from your HTML and CSS. This improves code organization and maintainability.
  • Write Modular Code: Break down your DOM manipulation logic into smaller, reusable functions. This makes your code easier to understand and reuse.

Conclusion

In conclusion, The Document Object Model (DOM) is a programming interface for web documents. By accessing, creating, modifying and deleting elements and their attributes in the DOM with Javascript, you can make changes to the webpage without having to reload the page.

In this beginners tutorial, we explored what DOM is and how Javascript interact with it using DOM API to access elements, modify them, add and remove elements from the DOM and add event listeners to elements.

Thank you for reading.