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

时间:2014-02-07 12:55:26

标签: javascript html dom

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

INPUT

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

输出

<body> 
 NEWfoo NEWbar 
   <div> 
      tatatata <hr><span> ooioi</span>
   </div>
 NEWbaz 
</body>

1 个答案:

答案 0 :(得分:0)

$(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
                }
            }
       );