I have:
<div>
Here
<a href="#"> is </a>
<p> Text, that I want to </p>
be removed
</div>
I want:
<div>
<a href="#"> </a>
<p> </p>
</div>
删除所有文本但保留 HTML 结构的最简单方法是什么?
您可以创建一个函数/插件,它将递归遍历顶级元素中的元素,删除找到的任何文本节点:
$.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();
JSFiddle http://jsfiddle.net/oGeez/tooe826z/1/
参考:
- .contents() https://api.jquery.com/contents/
- .each() https://api.jquery.com/each/
- .remove() https://api.jquery.com/remove/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)