Onjsdev

Share


Javascript DOM Tutorial


By onjsdev

Feb 22nd, 2024

DOM, which stands for Document Object Model, is an important concept in web development. Understanding the DOM is the first step to manipulate web pages, adding, removing, or modifying elements. Let's learn the basic principles of the DOM, its functionality, and how JavaScript interacts with it.

What is DOM?

The DOM 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.

what is DOM

Javascript and DOM

JavaScript can manipulate the DOM by accessing and modifying these nodes. For example, to change the text of a paragraph, you can first locate the paragraph node using JavaScript and then update the node's text property.

Now let's look at closely the basic DOM operations we can perform with Javascript.

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 and Tips

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:

Performance Considerations:

  • Batch DOM Manipulations: Minimize the number of interactions with the DOM for better performance.
  • Use Document Fragments: Append multiple nodes efficiently.

Cross-Browser Compatibility:

  • Feature Detection: Check if a feature is supported before using it.
  • Polyfills: Provide fallbacks for missing functionalities.

Conclusion

JavaScript DOM is a powerful tool that allows you to manipulate webpages dynamically. By accessing, creating, modifying and deleting elements and their attributes in the DOM, you can make changes to the webpage without having to reload the page.

In this tutorial, we explored how to use JavaScript DOM to access elements, modify them, add and remove elements from the DOM and add event listeners to elements. With these tools, you can create dynamic and interactive webpages.

Thank you for reading.