从HTML div中删除所有文本内容,但保留HTML标记和结构 [英] Remove all text content from HTML div but keep HTML tags and structure
本文介绍了从HTML div中删除所有文本内容,但保留HTML标记和结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
<div>
Here
<a href="#"> is </a>
<p> Text, that I want to </p>
be removed
</div>
我想:
<div>
<a href="#"> </a>
<p> </p>
</div>
删除所有文本的最简单方法是什么,但保留HTML结构?
What is the easiest way to remove all text, but keep the HTML Structure?
推荐答案
您可以创建一个函数/插件,它将递归顶级元素中的元素,删除找到的任何文本节点:
You can create a function/plugin that will recurse through elements in your top level element, removing any text nodes found:
$.fn.removeText = function(){
this.each(function(){
// Get elements contents
var $cont = $(this).contents();
// Loop through the contents
$cont.each(function(){
var $this = $(this);
// If it's a text node
if(this.nodeType == 3){
$this.remove(); // Remove it
} else if(this.nodeType == 1){ // If its an element node
$this.removeText(); //Recurse
}
});
});
}
$('#toplevel').removeText();
参考:
.contents()
.each()
.remove()
这篇关于从HTML div中删除所有文本内容,但保留HTML标记和结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文