Dom Met Document Getelementsbytagname
## XML DOM getElementsByTagName() Method
The `getElementsByTagName()` method returns a live `NodeList` containing all elements in the document with the specified tag name. The elements in the returned list are ordered in the sequence they appear in the source document.
---
## Syntax
```javascript
document.getElementsByTagName(name)
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `name` | `String` | The tag name of the elements to search for. Passing the wildcard string `"*"` will match all elements in the document. |
### Return Value
* A **live** `NodeList` (a collection of matching element nodes). If no matching elements are found, an empty `NodeList` is returned.
---
## Code Examples
### Example 1: Accessing the First Matching Element
The following code snippet loads an XML document (`books.xml`) and retrieves the text value of the first `` element:
```javascript
// Load the XML document
const xmlDoc = loadXMLDoc("books.xml");
// Get a NodeList of all elements and select the first one (index 0)
const titleElement = xmlDoc.getElementsByTagName("title");
// Access the text node value of the title element
const titleText = titleElement.childNodes.nodeValue;
// Output the result
document.write(titleText);
```
**Output:**
```text
Everyday Italian
```
---
### Example 2: Iterating Through All Matching Elements
You can loop through the returned `NodeList` to access or manipulate all elements of a specific tag:
```javascript
const xmlDoc = loadXMLDoc("books.xml");
const titles = xmlDoc.getElementsByTagName("title");
for (let i = 0; i < titles.length; i++) {
console.log(titles.childNodes.nodeValue);
}
```
---
### Example 3: Using the Wildcard Character `*`
To retrieve every single element node within the document, use the wildcard character `"*"`:
```javascript
const xmlDoc = loadXMLDoc("books.xml");
const allElements = xmlDoc.getElementsByTagName("*");
console.log("Total number of elements: " + allElements.length);
```
---
## Important Considerations
1. **Live Collection:** The returned `NodeList` is "live", meaning it automatically updates itself to reflect changes in the DOM tree. If you add or remove elements with the matching tag name later in your script, the collection will update instantly.
2. **Case Sensitivity:** In XML documents, tag names are **case-sensitive**. In HTML documents, `getElementsByTagName()` is case-insensitive.
3. **Element-level Method:** In addition to the `document` object, this method can also be called on any specific element node (e.g., `element.getElementsByTagName()`) to search only within that element's descendants.
YouTip