Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Strip all specific HTML tags from string

Tags:

jquery

I have a variable that contains a string of text and html tags, such as:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";

I would like to remove all tags of a certain type. Let's say all p and span tags for example.

This is the best I can come up with:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$("p", $temp).replaceWith("foo");
alert($temp.html());  //returns "Some text"

The closest response I could find is this answer by Nick Craver: strip span tags from string with jquery.

like image 691
iammatthew2 Avatar asked Jul 11 '12 22:07

iammatthew2


2 Answers

Demo: http://jsfiddle.net/VwTHF/1/

$('span, p').contents().unwrap();

.contents() will get the elements and text within each such tag, and .unwrap will remove the element wrapping each content section.

Based on your current approach it would look something like this:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";
var $temp = $(temp);
$temp.find('span, p').contents().unwrap().end().end();

If you want to continue targeting the original object, you have to use .end() to clear the filter.

like image 143
nbrooks Avatar answered Oct 01 '22 21:10

nbrooks


You could try the jquery plugin HTML Clean. In the example they provide:

$.htmlClean("<H1 class=\"header\"><P>Nested P Test</H1>", {format:true});

=> 
<h1>
        Nested P Test
</h1>

You can replace specific tags with {removeTags:[p]} and it will still render the contents just not the tag.

like image 40
scrappedcola Avatar answered Oct 01 '22 20:10

scrappedcola