views:

43

answers:

1

Hi,

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 html included). Once I have extracted the node's string, I'd like to modify it and write it back to the node. The modified text consists of text and html.

Is there any jquery method (or maybe Javascript) that can be used to get the text (without descending to the children) and another function that I can use to write back the text + html (plain text() and html() won't work in this case, as they would override the children nodes)?

Cheers, Max

+1  A: 

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/

patrick dw
Works great. Exactly what I was looking for... Would be fine to have it as part of jquery though.
Max