最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove text after <span> and append other text - Stack Overflow

programmeradmin1浏览0评论

I'm having a trouble with jQuery trying to remove a text after < span> tag to append other text.

Example:

<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>

I know how to append the text:

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

But how can I remove/clear the text after < /span> tag to append a new one?

I'm having a trouble with jQuery trying to remove a text after < span> tag to append other text.

Example:

<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>

I know how to append the text:

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

But how can I remove/clear the text after < /span> tag to append a new one?

Share Improve this question edited Dec 13, 2016 at 2:15 Victor asked Dec 13, 2016 at 1:36 VictorVictor 7623 gold badges15 silver badges33 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Assuming there are no other text nodes directly within #foo-id you could do something like:

$('#foo-id').html(function(){
   return $(this).children(); //only return elements, not text nodes
}).append('Some new text')
<script src="https://ajax.googleapis./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>

You can select .nextSibling of #span-id, set .textContent of #text node

$("#foo-id #span-id")[0].nextSibling.textContent = "abc123";
<script src="https://ajax.googleapis./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>

发布评论

评论列表(0)

  1. 暂无评论