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
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
javascript
dom
Share
Improve this question
asked Sep 11, 2016 at 14:22
Gideon IsaacGideon Isaac40555 silver badges1717 bronze badges5
2Can I see some code about this?
– Obinna Nwakwue
CommentedSep 11, 2016 at 14:37
If you don't want to destroy the actual DOM, then you need to search for all of them and bine them manually into the first of them and removing the other ones. Otherwise you could try by replacing Element.outerHTML by itself, which in most cases would result one text Node again. But what is the reason why you care about that?
– t.niese
CommentedSep 11, 2016 at 14:43
"There is no reason to have them": there seems no reason either to not have them. Leave this to the browser to manage.
– trincot
CommentedSep 11, 2016 at 15:21
I have a range application that depends on some stability in the DOM. So if every time the user selects some text a new text-node is created, pretty soon I have swiss cheese.
– Gideon Isaac
CommentedSep 11, 2016 at 16:33
Possible duplicate of Merging Text Nodes Together After Inserting Span
– Gaurang Tandon
CommentedJun 25, 2019 at 8:37
Add a ment
|
3 Answers
3
Reset to default
8
It seems that Node.normalize() is doing exactly what you want.
You can refer to: Node.normalize()
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);
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 bineTextNodes(node, prevText) {
if (node.nextSibling && node.nextSibling.nodeType == 3) {
nodesToDelete.push(node.nextSibling);
return bineTextNodes(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 = bineTextNodes(nodes[i], '');
}
}
for (i = 0; i < nodesToDelete.length; i++) {
console.log(nodesToDelete[i]);
nodesToDelete[i].remove();
}