jQuery:从HTML中删除文本

时间:2014-04-30 19:04:08

标签: jquery

我正在尝试从此HTML代码中删除“或”:

<div>
  <a href="https://store-b2aus7wd.mybigcommerce.com/account.php">Account</a>
  <a href='https://store-b2aus7wd.mybigcommerce.com/login.php' onclick=''>Sign in</a> 
 or
  <a href='https://store-b2aus7wd.mybigcommerce.com/login.php?action=create_account' onclick=''>Create an account</a>
</div>

使用此代码:

$("div").html().replace(/\or/g,"");

但它没有做任何事情。

3 个答案:

答案 0 :(得分:2)

$("div").html()以字符串形式返回div的当前html。然后你操纵。作为一个字符串。您需要将其分配回来:

$("div").html( $("div").html().replace(/\or/g,"") );

那就是说,你确定要用正则表达式这样做吗?如果字符&#34;或&#34;出现在他们被移除的其中一个网址中。

答案 1 :(得分:2)

不是将html用作字符串,而是通过使用DOM对象来做到这一点更好:

$('div').contents().filter(function() {
    return this.nodeType == 3 && $.trim(this.textContent) == 'or';
}).remove();

这是一个小提琴:http://jsfiddle.net/Lm4pC/。看起来.remove()对间距有奇怪的影响。根据您的具体情况,使用.replaceWith('\n').replaceWith(' ')可能会更好地运作:http://jsfiddle.net/kdYQP/

答案 2 :(得分:1)

只是发布这个以防你可以删除所有文本(截至目前它有点不清楚)并且不想使用正则表达式声明:

$("div").html($("div a"));

这会将div的HTML更改为仅包含a元素,实质上是从HTML中删除所有文本。在这种情况下,唯一的文本是or

Example