如何使用jQuery删除元素内的文本? [英] How to remove text inside an element with jQuery?

查看:95
本文介绍了如何使用jQuery删除元素内的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以创建一个具有如下结构的项目列表:

 < li> 
< div>有些东西< / div>
< a href =http://www.mysite.com/>新项目< / a>
(1票)
< / li>

我想知道是否有办法移除< div> < a> 标签,在这种情况下为(1票)字符串,带有jQuery或常规javascript。



预先感谢!

解决方案

b

  $(li)。contents()。filter(function(){return this.nodeType!= 1;})。remove(); 

或通过显式指定文本节点



<$ p $(li)。contents()。filter(function(){return this.nodeType == 3;})。remove();

请参阅小提琴


I have a script that creates a list of items with a structure like this:

<li>
    <div>Some stuff</div>
    <a href="http://www.mysite.com/">New Item</a> 
    (1 vote)
</li>

I was wondering if there was a way to remove everything outside the <div> and <a> tags, in this case the (1 vote) string, with jQuery or regular javascript.

Thanks in advance!

解决方案

This should work.

$("li").contents().filter(function(){ return this.nodeType != 1; }).remove();

or by specifying text nodes explicitly

$("li").contents().filter(function(){ return this.nodeType == 3; }).remove();

See this fiddle.

这篇关于如何使用jQuery删除元素内的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆