YouTip LogoYouTip

Dom Met Nodelist Item

## XML DOM NodeList item() Method The `item()` method returns the node at a specified index in a `NodeList` object. --- ## Definition and Usage A `NodeList` is a collection of nodes (such as elements, text nodes, or comments) returned by properties like `childNodes` or methods like `querySelectorAll()`. The `item()` method allows you to access a specific node within this list by passing its zero-based index. --- ## Syntax ```javascript nodeList.item(index) ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `index` | Number | Required. The zero-based index of the node you want to retrieve. | ### Return Value * **Node Object**: Returns the node at the specified index. * **null**: Returns `null` if the index is out of bounds (less than zero, or greater than or equal to the list's length). --- ## Bracket Notation vs. item() In JavaScript, you can access nodes in a `NodeList` using either the `item()` method or standard array-like bracket notation: ```javascript // Using item() var node = nodeList.item(0); // Using bracket notation var node = nodeList; ``` ### Key Differences: * **Out-of-bounds behavior**: If the index does not exist, `nodeList` returns `undefined`, whereas `nodeList.item(index)` returns `null`. * **Platform compatibility**: The `item()` method is part of the official W3C DOM specification, making it highly compatible across different XML/HTML parser environments (including non-browser environments). --- ## Important Considerations: Whitespace and Text Nodes Different browsers and XML parsers handle whitespace (spaces, tabs, and newlines) differently: * **Modern Browsers (Firefox, Chrome, Safari, Edge)**: Treat empty spaces or line breaks between elements as **text nodes** (`nodeType` of 3). * **Legacy Internet Explorer**: Historically ignored these empty whitespace text nodes. Because of this discrepancy, when iterating through `childNodes` using `item()`, you should always check the `nodeType` to ensure you are targeting element nodes (which have a `nodeType` of 1). --- ## Code Example The following example loads an XML file named `books.xml` into `xmlDoc` and loops through all child nodes of the root element. It uses `item()` to retrieve each node and filters out non-element nodes by checking their `nodeType`. ### Sample XML (`books.xml`) ```xml Harry Potter Learning XML ``` ### JavaScript Implementation ```javascript // Load the XML document var xmlDoc = loadXMLDoc("books.xml"); // Get the child nodes of the root element () var x = xmlDoc.documentElement.childNodes; for (var i = 0; i < x.length; i++) { // Check if the node is an Element Node (nodeType === 1) if (x.item(i).nodeType === 1) { // Output the node name document.write(x.item(i).nodeName); document.write("
"); } } ``` ### Output ```text book book ```
← Prop Nodemap LengthDom Prop Nodelist Length β†’