Javascript Removing Whitespace When It Shouldn't?

前端 未结 10 2040
谎友^
谎友^ 2020-12-11 05:29

I have a HTML file that has code similar to the following.


&         
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 05:57

    Edit: I am wrong, ignore me.

    You can get a text node's nodeValue, which should correctly represent its whitespace.

    Here is a function to recursively get the text within a given element (and it's library-safe, won't fail if you use something that modifies Array.prototype or whatever):

    var textValue = function(element) {
        if(!element.hasOwnProperty('childNodes')) {
            return '';
        }
        var childNodes = element.childNodes, text = '', childNode;
        for(var i in childNodes) {
            if(childNodes.hasOwnProperty(i)) {
                childNode = childNodes[i];
                if(childNode.nodeType == 3) {
                    text += childNode.nodeValue;
                } else {
                    text += textValue(childNode);
                }
            }
        }
        return text;
    };
    

提交回复
热议问题
Hello World