繁体   English   中英

是否有可能从某个元素中提取和修改所有文本段,而忽略所有嵌套的HTML标签? (在javascript中)

[英]Is it possible to extract and modify all text segments from some element ignoring all nested HTML tags? (in javascript)

是否有可能从某个元素中提取和修改所有文本段,而忽略所有嵌套的HTML标签? (在javascript中)。 例如:

输入

<body> 
 foo bar 
   <div> 
      tatatata <hr><span> ooioi</span>
   </div>
 baz 
</body>

输出值

<body> 
 NEWfoo NEWbar 
   <div> 
      tatatata <hr><span> ooioi</span>
   </div>
 NEWbaz 
</body>
$(document.body)
    .contents()   //use contents() to get the text nodes
        .each(    //Loop through all the elmenets
            function() {
                if(this.nodeType===3) { //Look for text nodes [enum is 3]
                    var txt = this.nodeValue || this.textContent;  //grab the text
                    this.nodeValue = this.textContent = "NEW" + txt + "NEW";  //set new value
                }
            }
       );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM