qadenza
qadenza

Reputation: 9293

how to remove specific tags and keep its content

I have some unwanted tags inside contenteditable divs and need to remove them.

Those are   and span

Tried with jquery unwrap function but but the result is undefined because it removes parent's tags and not the tags itself.

Any help? In the example below the expected console is:

lorem ipsum lorem ipsum lorem ipsum

$('button').on('click', function(){
  $('span').unwrap();
  console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='story' id='story'>
loem ipsum &nbsp;<span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>

Upvotes: 2

Views: 62

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115272

You need to unwrap the text nodes, so use contents() method to get all child nodes. And replace &nbsp; using String#replace method where html() method with a callback(the second argument in the callback is old HTML content) can be used for updating the content.

$('button').on('click', function() {

  // get span tags child nodes and unwrap
  $('#story span').contents().unwrap();

  // remove &nbsp; from html content
  $('#story').html((_, html) => html.replace(/&nbsp;/g, ''))

  console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='story' id='story'>
  loem ipsum &nbsp;<span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>

Upvotes: 1

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

you have to use like

$("#story").find("span").contents().unwrap();

$('button').on('click', function(){
  $("#story").find("span").contents().unwrap();
  console.log($('#story').html().replace(/&nbsp;/g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='story' id='story'>
loem ipsum &nbsp;<span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36594

You can change outerHTML to innerHTML for <span> and use replace to remove &nbsp;

$('button').on('click', function(){
  $('span').each(function(){
    this.outerHTML = this.innerHTML;
  })
  let html = $('#story').html();
  $('#story').html(html.replace(/&nbsp;/g,""))
  console.log($('#story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='story' id='story'>
loem ipsum &nbsp;<span style="font-size: 1.3em;">lorem ipsum</span> lorem ipsum
</div>
<br>
<button>CLICK</button>

Upvotes: 1

Related Questions