Return node text (non-recursive)

I would like to return the cell value of the node table. However, the text () method resets the entire DOM tree and returns a row of all nested nodes (a table cell may contain text and html). As soon as I retrieve the node string, I would like to modify it and write it back to the node. Modified text consists of text and html.

Is there any jQuery method (or maybe Javascript) that can be used to get text (without going down to children), and another function that I can use to write back text + HTML (plain text () and HTML () will not work in this case, since they will overlap the child nodes)?

Cheers, Max

+4
source share
1 answer

To get text from child text nodes, you can 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 when you go and replace it with the new text / html, you should do .each() instead and use .replaceWith() .

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

Here is an example: http://jsfiddle.net/ZNjCW/

+4
source