Return node text (non-recursive)

て烟熏妆下的殇ゞ 提交于 2020-01-24 06:27:13

问题


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:


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/



来源:https://stackoverflow.com/questions/3464647/return-node-text-non-recursive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!