Met Text Insertdata
## XML DOM CharacterData / Text insertData() Method
The `insertData()` method inserts a specified string into a `Text` or `CharacterData` node at a designated character offset. This method is highly useful when you need to modify the text content of an XML or HTML element dynamically without replacing the entire text node.
---
## Definition and Usage
The `insertData()` method inserts a string at a specified position within the existing text data of a node.
* **Target Nodes:** This method is inherited by the `Text` node interface from the `CharacterData` interface.
* **Zero-Based Indexing:** The starting position for the insertion is 0-indexed.
---
## Syntax
```javascript
characterDataNode.insertData(offset, data);
```
### Parameters
| Parameter | Type | Required / Optional | Description |
| :--- | :--- | :--- | :--- |
| `offset` | `Number` | **Required** | The character offset at which to insert the new string. The index starts at `0`. |
| `data` | `String` | **Required** | The string of text to be inserted. |
### Return Value
* This method does not return a value (`undefined`).
### Exceptions
* **INDEX_SIZE_ERR:** Thrown if the `offset` is negative or greater than the number of 16-bit units in the node's text data.
---
## Code Example
The following example demonstrates how to load an XML document (`books.xml`) and insert a prefix string into the text node of the first `` element.
### Sample XML File (`books.xml`)
Assume we have an XML file containing the following structure:
```xml
Everyday Italian
Giada De Laurentiis
2005
30.00
```
### JavaScript Implementation
```javascript
// Load the XML document
const xmlDoc = loadXMLDoc("books.xml");
// Access the text node of the first element
const titleTextNode = xmlDoc.getElementsByTagName("title").childNodes;
// Insert "Cooking: " at the very beginning (offset 0) of the text node
titleTextNode.insertData(0, "Cooking: ");
// Output the updated text content
console.log(titleTextNode.data);
```
### Output
```text
Cooking: Everyday Italian
```
---
## Key Considerations
1. **Text Nodes vs. Element Nodes:** Remember that `insertData()` cannot be called directly on an Element node (like ``). You must first target its child `Text` node (typically via `.childNodes` or `.firstChild`).
2. **In-Place Mutation:** This method modifies the existing text node in place. It does not create a new node or change the reference of the text node.
3. **Boundary Safety:** If the `offset` is equal to the length of the existing text, the new string is appended to the end of the text. If the `offset` exceeds the length of the text, a `DOMException` (INDEX_SIZE_ERR) is thrown.
YouTip