user516853
user516853

Reputation: 27

Strip certain html tags and return the rest of the string with all the other tags

I have a basic string with HTML tags in it. I want to remove the "span" tag and all of its contents and return the rest of the string and html.

When I do the following, it returns "here"...which is the contents of the matched query...I want to get everything else not the "span" stuff...what am I doing wrong?

var temp = '<div>Some text</div><p style="color:red">More text<span>here</span></p><p>Even more</p>';

var clean_temp = $(temp).find('span').remove();
var $temp = $(clean_temp).html(); //Returns "here"

alert($temp); // "here"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Views: 111

Answers (2)

Peter B
Peter B

Reputation: 24136

The jQuery remove() function removes and item and then returns the removed item, as you already seem to have discovered. The object from which it was removed is still also there, with its content modified.

Also in this case, due to the nature of your source string, doing $() on the source string returns a jQuery collection that wraps 3 separate DOM elements. Doing .find('span').remove() on that collection modifies the middle of these wrapped DOM elements. To reconstruct the HTML, we have to generate HTML from each wrapped DOM element and then join all these HTML parts together.

I created a helper function getHtml() for that purpose, see demo:

function getHtml(jqueryObj) {
  return jqueryObj.toArray().map(el => el.outerHTML).join("");
}

var temp = '<div>Some text</div><p style="color:red">More text<span>here</span></p><p>Even more</p>';

var $temp = $(temp);
console.log(getHtml($temp));

$temp.find('span').remove();
console.log(getHtml($temp));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Andreas Schrottenbaum
Andreas Schrottenbaum

Reputation: 116

You can replace it with an empty string:

var temp = `
<div>Some text</div>
<p style="color:red">
  More text <span>here</span>
</p>
<p>
  Even more
  <span>here as well</span>
</p>`;

// The modifier g looks global, not just the first hit and i is for case-insensitive
var expression = new RegExp(/<span(.*?)<\/span>/gi) // no closing '>' for elements with attributes
var clean_temp = temp.replace(expression, '')

console.log(clean_temp);

Upvotes: 0

Related Questions