Welcome to our comprehensive guide on JavaScript (JS) DOM Node Lists! In this lesson, we'll dive deep into understanding what Node Lists are, why they're essential for manipulating web pages, and how to work with them using various methods.
By the end of this lesson, you'll be equipped with the knowledge to manipulate elements on your web pages like a pro! 🚀
getElementsByTagName()getElementsByClassName()querySelectorAll()Node Lists in JavaScript are collections of elements that share a common factor, such as being of the same type or having the same class name. They are a powerful tool for manipulating web pages dynamically.
Node Lists are important because they allow you to easily access and manipulate multiple elements in a web page at once. Without them, you would have to manipulate each element individually, which can be time-consuming and error-prone.
To work with Node Lists, you can use three main methods: getElementsByTagName(), getElementsByClassName(), and querySelectorAll().
getElementsByTagName() 📝This method returns a Node List of all elements with a specified tag name.
// Get all paragraphs (<p>) on the page
const paragraphs = document.getElementsByTagName("p");getElementsByClassName() 📝This method returns a Node List of all elements with a specified class name.
// Get all elements with class "highlight"
const highlightedElements = document.getElementsByClassName("highlight");querySelectorAll() 📝This method returns a Node List of elements that match a specified CSS selector. It's more flexible than the previous two methods.
// Get all links (<a>) within the first paragraph
const firstParagraphLinks = document.querySelectorAll("p a");Once you have a Node List, you can manipulate its elements using various methods. Here are some examples:
// Change the content of all paragraphs
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].textContent = "New content!";
}// Change the class of all elements with class "highlight"
for (let i = 0; i < highlightedElements.length; i++) {
highlightedElements[i].classList.add("new-class");
}// Remove all links within the first paragraph
for (let i = 0; i < firstParagraphLinks.length; i++) {
firstParagraphLinks[i].remove();
}Now that you've learned the basics, let's dive into some practical examples!
This example demonstrates how to change the content of multiple elements based on user input.
This example shows how to sort a table dynamically based on column clicks.
Time for a quick quiz to reinforce what you've learned!
What method returns a Node List of all elements with a specified class name?