'can adjacent text nodes in the DOM be merged with Javascript?

Suppose I have a sentence in the webpage DOM that when I examine it, consists of 3 text nodes followed by perhaps some element like BOLD or ITALIC. I want to merge the text nodes into one text node, since having adjacent text nodes is meaningless - there is no reason to have them. Is there a way to merge them easily? Thanks



Solution 1:[1]

Maybe this will help you:

var parentNode = document.getElementById('pelements');
var textNode = document.createElement('p');

while (parentNode.firstChild) {
  textNode.textContent += parentNode.firstChild.textContent;
  parentNode.removeChild(parentNode.firstChild);
}

parentNode.appendChild(textNode);
<div id="pelements">
    <p>A</p>
    <p>B</p>
    <p>C</p>
  </div>

Solution 2:[2]

It seems that Node.normalize() is doing exactly what you want. You can refer to: Node.normalize()

Solution 3:[3]

It is possible, but you need to specify the parent element. It should be possible to traverse the whole DOM and every node, but if you can avoid that, it would be better.

nodes = document.body.childNodes;
nodesToDelete = [];

function combineTextNodes(node, prevText) {
    if (node.nextSibling && node.nextSibling.nodeType == 3) {
        nodesToDelete.push(node.nextSibling);
        return combineTextNodes(node.nextSibling, prevText + node.nodeValue);
    } else {
        return prevText + node.nodeValue;
    }
}

for (i = 0; i < nodes.length; i++) {
    if (nodes[i].nodeType == 3) {
        nodes[i].nodeValue = combineTextNodes(nodes[i], '');
    }
}

for (i = 0; i < nodesToDelete.length; i++) {
    console.log(nodesToDelete[i]);
    nodesToDelete[i].remove();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pawe? Miko?ajczyk
Solution 2 Hongfei
Solution 3 Makaze