`, or custom XML element) using DOM manipulation methods like `appendChild()` or `insertBefore()`.
---
## Definition and Usage
The `createTextNode()` method creates a raw text node containing the string passed to it.
Unlike setting `innerHTML`, using `createTextNode()` is highly secure because it automatically escapes HTML characters (such as `<` and `>`). This prevents Cross-Site Scripting (XSS) vulnerabilities when rendering user-supplied data.
* **Return Value:** A `Text` object representing the newly created text node.
---
## Syntax
```javascript
let textNode = document.createTextNode(text);
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `text` | `String` | Required. The string that specifies the text content of the node. |
---
## Code Examples
### 1. Basic XML DOM Example
The following example loads an XML file (`books.xml`) and appends a new `
");
}
```
### 2. HTML DOM Example (Web Development)
In web development, `createTextNode()` is commonly used alongside `createElement()` to safely inject text into a webpage.
```javascript
// 1. Create a new
Dom Met Document Createtextnode
## DOM Document.createTextNode() Method
The `createTextNode()` method is a fundamental part of the Web and XML DOM (Document Object Model). It is used to dynamically create a new text node with the specified text content.
Once created, this text node can be inserted into an element node (such as a `
`, `
element
let newDiv = document.createElement("div");
// 2. Create a text node with safe text content
let safeText = document.createTextNode("Hello, World! ");
// 3. Append the text node to the
newDiv.appendChild(safeText);
// 4. Append the
to the body of the document
document.body.appendChild(newDiv);
// Resulting HTML output:
//
Hello, World! <script>alert('safe')</script>
```
---
## Considerations and Best Practices
### 1. Security (XSS Prevention)
When you assign text to an element using `element.innerHTML = userInput`, the browser parses the string as HTML. If the input contains malicious scripts, they will execute.
Using `document.createTextNode(userInput)` ensures that the input is treated strictly as plain text, rendering any HTML tags harmlessly as text literals.
### 2. `createTextNode()` vs `textContent`
* **`createTextNode()`**: Creates an independent node object. It is useful when you need to build complex DOM structures step-by-step or insert text at specific positions among other child nodes.
* **`textContent`**: A property of an element (e.g., `element.textContent = "text"`). It is simpler and faster if you just want to replace all the text inside an existing element, as it clears any existing children and inserts the text in one step.
YouTip