在使用jquery插入之前删除元素

时间:2016-04-28 09:27:46

标签: javascript jquery

如何从#data中删除包含子跨度的跨度,以便#result包含“仅剩下文本”?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span>   €0,00</span> </span>
</div>
<div id="result"></div>

<script type="text/javascript">
  $(document).ready(function() {
    var nhtml = $('#data').html();
    $('#result').html(nhtml);
  });
</script>

2 个答案:

答案 0 :(得分:2)

使用 contents() filter() 从中过滤文本节点,然后通过 text()获取文字内容

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span>   €0,00</span> </span>
</div>
<div id="result"></div>

<script type="text/javascript">
  $(document).ready(function() {
    var nhtml = $('#data')
      .contents() // get all child nodes including  text and comment node
      .filter(function() {
        return this.nodeType == 3; // filter text node from it
      }).text(); // get the text content from it
    $('#result').html(nhtml);
  });
</script>
&#13;
&#13;
&#13;

使用 clone() 克隆元素并删除范围,然后获取html内容

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span>   €0,00</span> </span>
</div>
<div id="result"></div>

<script type="text/javascript">
  $(document).ready(function() {
    var nhtml = $('#data')
      .clone() // clone the element
      .find('.price') // get the span
      .remove() // remove the span
      .end() // back to cloned element
      .html(); // get the html content from cloned element 
    $('#result').html(nhtml);
  });
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我使用.remove()函数删除它,你可以参考下面的小提琴链接

$( document ).ready(function() {
$(".price").remove();
  var nhtml = $('#data').html();
  $('#result').html(nhtml);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span>   €0,00</span> </span> </div>
<div id="result"> </div>

Jsfiddle link for solution