Josh L Josh L - 3 months ago 10
Javascript Question

Using JQuery to parse out element tags but not its contents

I have a string that contains html and I want to remove the entire span element but not its contents from the string (I want to leave the word Canadian and any other elements).

var htmlString =
<p>The Royal <span class="highlight-keyword highlight-keyword-2 highlight-pid-28" style="font-weight: bold;">Canadian<span> Navy (RCN) is the naval force of Canada.<p>
<p>As of 2015 <span class="highlight-keyword highlight-keyword-2 highlight-pid-28" style="font-weight: bold;">Canada's</span> navy operates 1 destroyer, 12 frigates, 4 patrol submarines, 12 coastal defence vessels and 8 unarmed patrol/training vessels, as well as several auxiliary vessels.</p>


Now if I was manipulating the DOM I could simply use

$(this).find("span.highlight-keyword").each(function () {
$(this).contents.unwrap();
})


But I am not manipulating the DOM I am manipulating a string and I want to return the entire string without the span element but keeping everything else.

Answer
var htmlString = "<p>The Royal <span class='highlight-keyword highlight-keyword-2 highlight-pid-28' style='font-weight: bold;'>Canadian<span> Navy  (RCN) is the naval force of Canada.<p><p>As of 2015 <span class='highlight-keyword highlight-keyword-2 highlight-pid-28' style='font-weight: bold;'>Canada's</span> navy operates 1 destroyer, 12 frigates, 4 patrol submarines, 12 coastal defence vessels and 8 unarmed patrol/training vessels, as well as several auxiliary vessels.</p>"

var cleanString = $(htmlString).find('span').each(function() {
  $(this).contents().unwrap();
}).end().appendTo('<div/>').parent().html();

console.log(cleanString)

https://jsfiddle.net/SeanWessell/5a23stwq/

Create jQuery object from HTML. For each span unwrap the contents. AppendTo temporary object which will now be the parent however is never attached to the DOM. Return html() function off the temp object as parent.

Results from console:

<p>The Royal Canadian Navy  (RCN) is the naval force of Canada.</p><p></p><p>As of 2015 Canada's navy operates 1 destroyer, 12 frigates, 4 patrol submarines, 12 coastal defence vessels and 8 unarmed patrol/training vessels, as well as several auxiliary vessels.</p>
Comments