Skip to content Skip to sidebar Skip to footer

Return Node Text (non-recursive)

I'd like to return a table cell's node value. The method text() however, goes down the whole DOM tree and returns a string of all nested nodes (the table cell may have text and htm

Solution 1:

To get the text from child text nodes, you could do this:

var text = $('selector').contents().map(function() {
        // If it is a textNode, return its nodeValue
    if(this.nodeType == 3) return this.nodeValue;
}).get().join('');​​​​​​

I don't know exactly what you want to do with the text, but if you want to process it as you go and replace it with new text/html, you should be able to do an .each() instead and use .replaceWith().

$('selector').contents().each(function() {
    if(this.nodeType == 3) {
       // do something with the text
       $(this).replaceWith('new processed value');
    }
});​​​​​​

Here's an example: http://jsfiddle.net/ZNjCW/


Post a Comment for "Return Node Text (non-recursive)"