Creating Text Nodes with createTextNode in JavaScript
The document.createTextNode()
method creates a text node without wrapping it in an HTML
tag. It’s useful when you want to add plain text to an element without altering its structure.
let textNode = document.createTextNode('Dxrkd3v was here');
Example of inserting text into a paragraph using pure JS
without modifying the HTML
:
let p = document.createElement('p');
let t = document.createTextNode('Hello, Cxd3!');
p.appendChild(t);
document.body.appendChild(p);
This method also lets you change text on the fly:
let div = document.getElementById('h1');
div.appendChild(document.createTextNode('New h1!'));
createTextNode()
is a cool way to add text without touching the document’s structure. It gives you precise control over content while preserving the existing HTML
.