PepperoniPizza
PepperoniPizza

Reputation: 9102

Strip content of specific tags

I can strip the html correctly out of a string doing this:

HtmlToText = function(html){
    return jQuery(html).text();
};

but there is cases then the HTML string containing styling like:

<style type="text/css">
.button:hover {
    background-color: #6B6D71;
}
</style>

the function will strip the <style> tags but my text will end up with
.button:hover { background-color: #6B6D71; }

I'll like to know if jQuery is able to strip styles too and how.

Upvotes: 0

Views: 94

Answers (2)

isherwood
isherwood

Reputation: 61036

You can use the remove() method to target just style tags without much overhead cost:

HtmlToText = function(html){
    return jQuery(html).remove('style').text();
};

Demo

Upvotes: 2

Bill Criswell
Bill Criswell

Reputation: 32921

You can use .clone() and remove the style tags from that using .remove().

var $foo = $('.foo'),
    $fooClone = $foo.clone();

$fooClone.find('style').remove();

$('#output').text($fooClone.text());

Here is a small demo: http://jsbin.com/lamasabapu/1/edit?html,css,js,output

Upvotes: 2

Related Questions