Text node and DocumentFragment node

Text node concept

The text node (Text) represents the text content of the element node (Element) and the attribute node (Attribute). If a node only contains a paragraph of text, then it has a text child node, which represents the text content of the node.

Usually we use the firstChild, nextSibling and other attributes of the parent node to get the text node, or use the createTextNode method of the Document node to create a text node.

// Get the text node
var textNode = document.querySelector("p").firstChild;

// Create text node
var textNode = document.createTextNode("Hi");
document.querySelector("div").appendChild(textNode);

The browser natively provides a Text constructor. It returns an instance of a text node. Its parameter is the text content of the text node.

// empty string
var text1 = new Text();

// non-empty string
var text2 = new Text("This is a text node");

Note that since a space is also a character, even if there is only one space, a text node will be formed. For example, <p> </p> contains a space, and its child node is a text node.

In addition to inheriting the Node interface, the text node also inherits the CharacterData interface. For the properties and methods of the Node interface, please refer to the chapter "Node Interface", which will not be repeated here. Most of the following properties and methods come from the CharacterData interface.

Text node attributes

data

The data property is equivalent to the nodeValue property, which is used to set or read the content of a text node.

// read text content
document.querySelector("p").firstChild.data;
// Equivalent to
document.querySelector("p").firstChild.nodeValue;

// Set the text content
document.querySelector("p").firstChild.data = "Hello World";

wholeText

The wholeText attribute returns the current text node and the adjacent text node as a whole. In most cases, the return value of the wholeText property is the same as the data property and the textContent property. However, there are differences in some special circumstances.

For example, the HTML code is as follows.

<p id="para">A <em>B</em> C</p>

At this time, the wholeText attribute and the data attribute of the text node return the same value.

var el = document.getElementById("para");
el.firstChild.wholeText; // "A "
el.firstChild.data; // "A "

However, once the <em> node is removed, there will be a difference between the wholeText property and the data property, because at this time there are actually two adjacent text nodes under the <p> node.

el.removeChild(para.childNodes[1]);
el.firstChild.wholeText; // "A C"
el.firstChild.data; // "A "

length

The length property returns the text length of the current text node.

new Text("Hello").length; // 5

nextElementSibling, previousElementSibling

The nextElementSibling property returns the sibling element node immediately following the current text node. If the element node cannot be retrieved, null is returned.

// HTML is
// <div>Hello <em>World</em></div>
var tn = document.querySelector("div").firstChild;
tn.nextElementSibling;
// <em>World</em>

The previousElementSibling property returns the nearest sibling element node before the current text node. If the element node is not available, null: is returned.

Text node method

appendData(), deleteData(), insertData(), replaceData(), subStringData()

The following 5 methods are all methods to edit the text content of the Text node.

-appendData(): Append a string to the end of the Text node. -deleteData(): Delete the substring inside the Text node. The first parameter is the starting position of the substring, and the second parameter is the length of the substring. -insertData(): Insert a string in the Text node, the first parameter is the insertion position, and the second parameter is the inserted substring. -replaceData(): Used to replace text, the first parameter is the starting position of the replacement, the second parameter is the length to be replaced, and the third parameter is the newly added string. -subStringData(): used to get the substring, the first parameter is the starting position of the substring in the Text node, and the second parameter is the length of the substring.

// HTML code is
// <p>Hello World</p>
var pElementText = document.querySelector("p").firstChild;

pElementText.appendData("!");
// The page displays Hello World!
pElementText.deleteData(7, 5);
// The page displays Hello W
pElementText.insertData(7, "Hello");
// The page displays Hello WHello
pElementText.replaceData(7, 5, "World");
// The page displays Hello WWorld
pElementText.substringData(7, 10);
// The page display remains unchanged and returns to "World"

remove()

The remove method is used to remove the current Text node.

// HTML code is
// <p>Hello World</p>
document.querySelector("p").firstChild.remove();
// Now the HTML code is
// <p></p>

splitText()

The splitText method splits the Text node into two and becomes two adjacent Text nodes. Its parameter is the segmentation position (starting from zero), and the segmentation ends before the character at that position. If the split position does not exist, an error will be reported.

After the split, this method returns the string behind the split position, and the original Text node becomes only the string before the split position.

// The html code is <p id="p">foobar</p>
var p = document.getElementById("p");
var textnode = p.firstChild;

var newText = textnode.splitText(3);
newText; // "bar"
textnode; // "foo"

The normalize method of the parent element node can merge two adjacent Text nodes.

Following the example above, the splitText method of the text node splits a Text node into two, and the normalize method of the parent element can perform the reverse operation and merge them.

p.childNodes.length; // 2

// merge two adjacent Text nodes
p.normalize();
p.childNodes.length; // 1

DocumentFragment node

The DocumentFragment node represents a fragment of a document, which itself is a complete DOM tree structure. It has no parent node, parentNode returns null, but any number of child nodes can be inserted. It does not belong to the current document, and manipulating the DocumentFragment node is much faster than manipulating the DOM tree directly.

It is generally used to build a DOM structure and then insert the current document. The document.createDocumentFragment method and the browser's native DocumentFragment constructor can create an empty DocumentFragment node. Then use other DOM methods to add child nodes to it.

var docFrag = document.createDocumentFragment();
// Equivalent to
var docFrag = new DocumentFragment();

var li = document.createElement("li");
li.textContent = "Hello World";
docFrag.appendChild(li);

document.querySelector("ul").appendChild(docFrag);

The above code creates a DocumentFragment node, then adds a li node to it, and finally moves the DocumentFragment node to the original document.

Note that the DocumentFragment node itself cannot be inserted into the current document. When it is used as a parameter of methods such as appendChild(), insertBefore(), and replaceChild(), all of its child nodes are inserted into the current document instead of itself. Once the DocumentFragment node is added to the current document, it itself becomes an empty node (the textContent attribute is an empty string) and can be used again. If you want to save the contents of the DocumentFragment node, you can use the cloneNode method.

document.querySelector("ul").appendChild(docFrag.cloneNode(true));

Adding the DocumentFragment node above to enter the current document will not clear the DocumentFragment node.

The following is an example of using DocumentFragment to reverse the order of all child nodes of a specified node.

function reverse(n) {
  var f = document.createDocumentFragment();
  while (n.lastChild) f.appendChild(n.lastChild);
  n.appendChild(f);
}

The DocumentFragment node object does not have its own properties and methods, all inherited from the Node node and the ParentNode interface. In other words, the DocumentFragment node has the following four more attributes than the Node node.

-children: returns a dynamic HTMLCollection collection object, including all child element nodes of the current DocumentFragment object. -firstElementChild: Returns the first child element node of the current DocumentFragment object, or returns null if there is none. -lastElementChild: Returns the last child element node of the current DocumentFragment object, or returns null if there is none. -childElementCount: Returns the number of all child elements of the current DocumentFragment object.