2

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>

2
  • you set the #data html to Only text left like $('#data').html('Only text left') Commented Apr 28, 2016 at 9:30
  • Problem here, content is dynamic. This is not an option. Commented Apr 28, 2016 at 9:31

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@Kurdt94 : glad to help you :)
0

I have used .remove() function to remove it, you can refer the fiddle link below

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.