HTML NodeList keys()
Method: Getting NodeList Keys
The keys()
method in the HTML DOM (Document Object Model) provides a way to retrieve the keys of the nodes within a NodeList
. Since a NodeList
is an ordered collection of nodes, the keys are simply the indices of the nodes. This method returns an iterator that allows you to loop through these keys. Understanding how to use keys()
can be very helpful when you need to access the indices while iterating through a NodeList
.
What is a NodeList
?
A NodeList
is a collection of nodes extracted from a document. It is an array-like object representing a set of elements. NodeList
objects are commonly returned by methods like document.querySelectorAll()
and properties like childNodes
.
Purpose of the keys()
Method
The primary purpose of the keys()
method is to provide an iterator for the keys (indices) of the nodes in a NodeList
. This is useful when you need to know the index of each node as you iterate through the list.
Syntax
The keys()
method does not take any arguments and returns an iterator object.
let iterator = nodeList.keys();
nodeList
: TheNodeList
object from which to retrieve the keys.iterator
: An iterator object that yields the keys (indices) of theNodeList
.
Examples
Let’s explore some examples that demonstrate how to use the keys()
method effectively.
Basic Example: Retrieving Node Indices
In this example, we retrieve all the <li>
elements within a <ul>
element and then use the keys()
method to iterate through the indices of the nodes.
<!DOCTYPE html>
<html>
<head>
<title>NodeList keys() Example</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const list_keys = document.getElementById("myList");
const items_keys = list_keys.querySelectorAll("li");
const iterator_keys = items_keys.keys();
for (const key of iterator_keys) {
console.log("Index:", key);
}
</script>
</body>
</html>
Output in Console:
Index: 0
Index: 1
Index: 2
This basic example illustrates how the keys()
method allows you to access the index of each <li>
element in the NodeList
.
Using keys()
with forEach()
You can combine the keys()
method with the forEach()
method to iterate through the NodeList
and access both the index and the node itself.
<!DOCTYPE html>
<html>
<head>
<title>NodeList keys() with forEach() Example</title>
</head>
<body>
<ul id="myListForEach">
<li>Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
<script>
const list_foreach = document.getElementById("myListForEach");
const items_foreach = list_foreach.querySelectorAll("li");
const keys_iterator_foreach = items_foreach.keys();
const keysArray_foreach = Array.from(keys_iterator_foreach);
keysArray_foreach.forEach((key) => {
const node = items_foreach[key];
console.log("Index:", key, "Node:", node.textContent);
});
</script>
</body>
</html>
Output in Console:
Index: 0 Node: Item A
Index: 1 Node: Item B
Index: 2 Node: Item C
Here, we convert the iterator to an array to use the forEach
method to iterate through the keys and log both the index and the text content of each list item.
Creating a Dynamic List with Indices
In this example, we dynamically create a list with numbered items based on the indices obtained from the keys()
method.
<!DOCTYPE html>
<html>
<head>
<title>NodeList Dynamic List with Indices Example</title>
</head>
<body>
<ul id="dynamicList">
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<div id="outputDiv"></div>
<script>
const list_dynamic = document.getElementById("dynamicList");
const items_dynamic = list_dynamic.querySelectorAll("li");
const iterator_dynamic = items_dynamic.keys();
let output_dynamic = "";
for (const key of iterator_dynamic) {
output_dynamic += `<p>Item ${key + 1}: ${items_dynamic[key].textContent}</p>`;
}
document.getElementById("outputDiv").innerHTML = output_dynamic;
</script>
</body>
</html>
Output:
<p>Item 1: Apple</p>
<p>Item 2: Banana</p>
<p>Item 3: Cherry</p>
This example generates a dynamic list where each item is numbered based on its index in the NodeList
.
Using keys()
with Array.from()
The keys()
method returns an iterator, which can be converted into an array using Array.from()
. This allows you to use array methods on the keys.
<!DOCTYPE html>
<html>
<head>
<title>NodeList keys() with Array.from() Example</title>
</head>
<body>
<ul id="arrayList">
<li>Dog</li>
<li>Cat</li>
<li>Bird</li>
</ul>
<script>
const list_array = document.getElementById("arrayList");
const items_array = list_array.querySelectorAll("li");
const iterator_array = items_array.keys();
const keysArray_array = Array.from(iterator_array);
console.log("Keys Array:", keysArray_array);
keysArray_array.forEach(key => {
console.log(`Index ${key}: ${items_array[key].textContent}`);
});
</script>
</body>
</html>
Output in Console:
Keys Array: [0, 1, 2]
Index 0: Dog
Index 1: Cat
Index 2: Bird
This example demonstrates converting the iterator from keys()
into an array and then iterating through the array to access the indices and corresponding node values.
Real-World Use Case: Modifying List Items Based on Index
In a more complex scenario, you might want to modify list items based on their index. Hereβs how you can use the keys()
method to achieve this:
<!DOCTYPE html>
<html>
<head>
<title>NodeList Modifying List Items Example</title>
</head>
<body>
<ul id="modifyList">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<script>
const list_modify = document.getElementById("modifyList");
const items_modify = list_modify.querySelectorAll("li");
const iterator_modify = items_modify.keys();
for (const key of iterator_modify) {
if (key % 2 === 0) {
items_modify[key].style.color = "red";
} else {
items_modify[key].style.color = "blue";
}
}
</script>
</body>
</html>
In this example, list items with even indices are colored red, while those with odd indices are colored blue. This shows how the keys()
method can be used to perform conditional modifications based on the index of each node.
Conclusion
The keys()
method of the HTML NodeList
object is a valuable tool for retrieving the indices of nodes within a NodeList
. By providing an iterator for these keys, it allows you to iterate through the NodeList
and access the index of each node, enabling more complex and controlled manipulations. Whether you’re creating dynamic lists, modifying elements based on their position, or simply needing to keep track of indices during iteration, the keys()
method provides a straightforward and efficient solution.