Chuck's Academy

DOM Manipulation in JavaScript

Selecting Elements in the DOM

Selecting elements in the DOM is a fundamental skill for any web developer. It allows us to locate and work with specific elements within the HTML document. In this chapter, we will explore different methods for selecting elements in the DOM using JavaScript.

Selecting Elements by ID

The simplest and most direct method to select an element is to use its ID. IDs must be unique within an HTML document.

javascript

Selecting Elements by Class

We can select all elements that have a specific class using getElementsByClassName.

javascript

Selecting Elements by Tag

To select all elements of a specific tag type, we use getElementsByTagName.

javascript

Selecting Elements with CSS Selectors

The querySelector and querySelectorAll methods allow us to select elements using CSS selectors. This gives us great flexibility.

  • document.querySelector(selector): Selects the first element that matches the CSS selector.
  • document.querySelectorAll(selector): Selects all elements that match the CSS selector.

Example of querySelector and querySelectorAll

javascript

Differences between HTMLCollection and NodeList

  • HTMLCollection: It is a live collection of document elements. If the DOM changes, the collection updates automatically.
  • NodeList: It can be static or live, depending on the method that generated it. NodeLists returned by querySelectorAll are static, meaning they do not change if the document is updated.

Iterating through Collections of Elements

We can iterate through both HTMLCollection and NodeList using loops.

javascript

Conclusion

The ability to efficiently select elements is crucial for DOM manipulation. By using different selection methods, we can easily access any part of our document. In the upcoming chapters, we will start manipulating these elements by modifying their attributes, content, and structure.


Ask me anything