Kurdt94 Kurdt94 - 7 months ago 13
Javascript Question

Remove element before inserting with jquery

How do I remove the span with child span from #data, so that #result contains "Only text left" ?



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




Answer

Filter text nodes from it using contents() and filter(), then get text content by text()

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


Or clone the element using clone() and remove the span, then get the html content

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