Size limit to javascript [node].nodeValue field?

僤鯓⒐⒋嵵緔 提交于 2019-11-29 15:41:32

Check this. It says:

"Also important to note is that although the specifications say that no matter how much text exists between tags, it should all be in one text node, in practice this is not always the case. In Opera 7-9.2x and Mozilla/Netscape 6+, if the text is larger than a specific maximum size, it is split into multiple text nodes. These text nodes will be next to each other in the childNodes collection of the parent element."

@Kooilnc has it right, 4k limit on text nodes in Firefox.

You can work around it by doing this:

function getNodeText(xmlNode) {
    if(!xmlNode) return '';
    if(typeof(xmlNode.textContent) != "undefined") return xmlNode.textContent;
    return xmlNode.firstChild.nodeValue;
}

text = getNodeText(document.getElementsByTagName("div").item(0));
alert(text.length);

See it in action here: http://jsfiddle.net/Bkemk/2/

Function borrowed from here: http://www.quirksmode.org/dom/tests/textnodesize.html

What I've come up with instead of targeting a single node:

function getDataOfImmediateChild(parentTag, subTagName)
{
    var val = "";
    var listOfChildTextNodes;
    var directChildren = parentTag.childNodes;

    for (m=0; m < directChildren.length; m++)
    {
        if (directChildren[m].nodeName == subTagName)
        {
           /* Found the tag, extract its text value */
           listOfChildTextNodes = directChildren[m].childNodes;
           for (n=0; n < listOfChildTextNodes.length; n++)
           {
              if (typeof listOfChildTextNodes[n] == "TextNode")
                val += listOfChildTextNodes[n].nodeValue;
           }
         }
    }
    return val;

It might be worthwhile to also ensure the listOfChildTextNodes[n] element is a TextNode.

@Ryley

The only reason I do an iteration over the direct children is because getElementsByTagName and getElementsById will return nodes that are farther down the hierarchy. Better explained as an example:

<foo>
  <bar>
    <zoo>
       <bar>-</bar>
    </zoo>     
   <bar></bar>
</zoo>

If I say fooTag.getElementsByTagName("bar"), it's going to return an array of both s, even though I only want the second (since it's the only true child of ). The only way I can think of enforcing this "search only my direct children" is by iterating over the children.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!