简体   繁体   中英

Prevent Normalization of Text Nodes

On the current project that I'm working on, I'm splitting certain text nodes into multiple nodes so that I can keep track of them. I'm storing these nodes inside a global object somewhere, but for some reason they keep normalizing sometime in between when I need them and when they're parsed. It doesn't happen immediately, oddly enough, but I can't figure out how to prevent it...

Example:

<p>
    foo
    bar
    **HELLO**
</p>

In the above example there is one text node: "foo\n bar\n **HELLO**" . I want to split this node into three separate text nodes, while keeping track of the last one.

However, after creating the new text node, populating it, and then appending it to its' parent ( <p> ) it becomes normalized a short while after I append it.

I need to keep it from normalizing.

A simple code example would be to use the following:

var pElem = document.querySelector('p'),
    textNode = pElem.childNodes[0],
    newNodes = textNode.nodeValue.split(/\s+/g).reverse().map(function(i,v){
        return document.createTextNode(v);
    }),
    curNode = textNode;

textNode.nodeValue = newNodes[0].nodeValue;

for(var x=1;x<newNodes.length;x++) {
    curNode.parentNode.insertBefore(curNode, newNodes[x]);
    curNode = newNodes[x]
}

var lastNode = newNodes[0]; // THIS is what I need to keep track of

I didn't test this code; just whipped it up. Basically, after a while they all merge into one text node (aka, "normalize").

There is no other code that may be executing Node.normalize() . This is occurring in an isolated test page where no other code is introduced (as in none ; no other libraries, polyfills, etc.).

Hope this helps guys!

It would be nice if there were a way to mark specific text nodes as unnormalizable.

In the absence of that capability, comment nodes before and after as guards can be used to prevent otherwise-adjacent-text-node merging.

I suggest &zwnj; as a non-displaying placeholder to prevent otherwise-empty nodes from being removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM