slifty
slifty

Reputation: 13821

Javascript textContent (whitespace preserving innerText) for IE

I need the IE equivalent of textContent.

Before you jump off the seat of your pants -- innerText is NOT the same as textContent. innerText parses whitespace as the DOM renderer parses. textContent parses whitespace as it is written. I need the latter, but I.E. doesn't support textContent.

For instance:

DOM Obj:   <p>This  is  an  example.</p>
innerText:   "This is an example."
textContent: "This  is  an  example."

Upvotes: 2

Views: 2742

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075219

I don't think you can. IE "normalizes" the spaces even within the TextNode#nodeValue property. A while back I'd written this:

function textValue(element) { 
    var collector = []; 
    textValueCollector(element, collector); 
    return collector.join(""); 
} 
function textValueCollector(element, collector) { 
    var node; 
    for (node = element.firstChild; node; node = node.nextSibling) 
    { 
        switch (node.nodeType) { 
            case 3: // text 
            case 4: // cdata 
                collector.push(node.nodeValue); 
                break; 
            case 8: // comment 
                break; 
            case 1: // element 
                if (node.tagName == 'SCRIPT') { 
                    break; 
                } 
                // FALL THROUGH TO DEFAULT 
            default: 
                // Descend 
                textValueCollector(node, collector); 
                break; 
        } 
    } 
}

And so I thought it might be what you needed, but sadly, no. As you can see in this live example, on IE the extra spaces are left out even though we're walking the text nodes directly, so it only shows a length of 45 where it's 61 in reality (and on other browsers [Chrome, Firefox, Opera]).

Upvotes: 1

Related Questions