删除<span>后的文本并附加其他文本

时间:2016-12-13 01:36:27

标签: javascript jquery html

我遇到了jQuery尝试在&lt;之后删除文本的问题。跨度&GT;标记以附加其他文本。

示例:

<div id="foo-id">  
    <span id="span-id">  
        <i id="icon-id" class="fa fa-square-o"></i>  
    </span> text..here... (this text needs to be removed)
</div>

我知道如何附加文字:

$('#foo-id').after()[0].append('this is a text');

但是如何在&lt;之后删除/清除文本? /跨度&GT;标签添加一个新的?

2 个答案:

答案 0 :(得分:8)

假设#foo-id中没有其他文本节点,您可以执行以下操作:

&#13;
&#13;
$('#foo-id').html(function(){
   return $(this).children(); //only return elements, not text nodes
}).append('Some new text')
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo-id">  
    <span id="span-id">  
        <i id="icon-id" class="fa fa-square-o"></i>  
    </span> text..here... (this text needs to be removed)
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以选择.nextSibling #span-id,设置.textContent节点的#text

$("#foo-id #span-id")[0].nextSibling.textContent = "abc123";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo-id">  
    <span id="span-id">  
        <i id="icon-id" class="fa fa-square-o"></i>  
    </span> text..here... (this text needs to be removed)
</div>