Pregunta

i am using nicedit as editor in my app and the users of our website use to paste data from MS word or some other sources, hence the ui breaks up, so we have decided to remove all formatting from the html using jquery.

What i did is removed all inline style and class, but it is creating problem as it is removing bold and italics too, where as we want to retain it.

is their any simple way of removing all style except bold using jquery.

example :

<div style="color:red; font-size:13px; font-weight:bold;">test div </div>

in the above element i want it as

<div style="font-weight:bold;">test div </div>
¿Fue útil?

Solución 2

I think the only way is to store the styles you want, remove them all and then set them again.

$('.selector').each(function() {
  var keepStyle, $el;
  $el = $(this);
  keepStyle = {
    font-weight: $el.css('font-weight'),
    font-style : $el.css('font-style')
  };

  $el.removeAttr('style')
    .css(keepStyle);
})

Otros consejos

I havent tested it try if it works

 $('div').each(function(){
   weight = $(this).css('font-weight');
   $(this).attr('style','');
   $(this).removeClass();
   $(this).css('font-weight',  weight);
});

You can store this attributes as data using jquery data method and restore after clearing all styles

var $temp = $('<div><div style="color:red; font-size:13px; font-weight:bold;">test div </div></div>');

 $temp.find('*').each(function(){
    var fontWeight = $(this).css('font-weight');
$(this).removeAttr('style');
if(fontWeight!=undefined){
     $(this).attr('style','font-weight:'+fontWeight);
}
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top