Remove all text between div without losing text outside of it - jQuery JS

I have text that is stored in a variable like this:

<div class="foo">text inside div</div>
outside text here.


I want to remove all div and text in it and keep the outer text.


source to share

2 answers

Create an HTML based element. Then,

$('.foo', context).remove();


For example:

var text = "<div class=\"foo\">text inside div</div>\noutside text here.";
var xml = $('<root>' + text + '</root>');
$('.foo', xml).remove();
text = xml.html();




You can use after

to insert inner text after the div and then remove it:

var $foo = $(".foo"); 


Or, you can use a function replaceWith

to replace the div element with your inner text content:





All Articles