Ways of setting/getting a textNode's value

416 views Asked by At

There are many ways to retrieve/change the value of a text node:

I tend to use .data. Which of them is recommended - they all return the same?

1

There are 1 answers

0
jasssonpet On

If you have a TEXT_NODE [type 3] textContent will return the nodeValue (MDN):

If the node is a CDATA section, a comment, a processing instruction, or a text node, textContent returns the text inside this node (the nodeValue).

CharacterData is the same as nodeValue for text nodes (MDN).

Text, Comment, and CDATASection all implement CharacterData, which in turn also implements Node.

For text nodes they are the same.

jQuery (Sizzle) uses nodeValue:

/**
 * Utility function for retreiving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
var getText = Sizzle.getText = function( elem ) {
    ...
    if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
        // Use textContent || innerText for elements
        if ( typeof elem.textContent === 'string' ) {
            return elem.textContent;
        } else if ( typeof elem.innerText === 'string' ) {
            // Replace IE's carriage returns
            return elem.innerText.replace( rReturn, '' );
        }
        ...
    // TEXT_NODE
    } else if ( nodeType === 3 || nodeType === 4 ) {
        return elem.nodeValue;
    }
    return ret;
};

So using data is fine, but textContent is IE9+ only and a bit slower.