How to Use Javascript to Count the Number of Nodes in XML
The JavaScript function "getElementsByTagName" retrieves the number of nodes and returns an array of records. You use this array to determine the number of nodes returned, so you can loop through each record. The number of records lets you loop through the array, so you do not receive a JavaScript error for retrieving a null value.
Instructions
-
-
1
Right-click the HTML file that opens the XML file. Click "Open With," then double-click your preferred JavaScript or HTML editor.
-
2
Retrieve the root element. The root element defines the set of records such as a list of customers or orders. Type the following code in the JavaScript function that opens the XML file: "var root = doc.documentElement;" (without quotes).
-
-
3
Get a list of records. The following code retrieves a list of records from the root node: "var nodes = root.getElementsByTagName('customers');" (without quotes). Replace the "customers" text with the node list you want to retrieve.
-
4
Identify the number of nodes. The following code uses the new "nodes" array to identify the number of nodes: "var count = nodes.Count;".
-
1