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.
+2
Amir
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();
+4
strager
source
to share
You can use after
to insert inner text after the div and then remove it:
var $foo = $(".foo");
$foo.after($foo.text()).remove();
Or, you can use a function replaceWith
to replace the div element with your inner text content:
$foo.replaceWith($foo.text());
+1
CMS
source
to share