开发者

Return node text (non-recursive)

开发者 https://www.devze.com 2023-01-11 09:49 出处:网络
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'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 met开发者_开发技巧hod (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


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消