简体   繁体   中英

how to remove all style except font-weight using jquery in all elements

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>

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);
});

您可以使用jquery数据方法将此属性存储为数据,并在清除所有样式后还原

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);
})
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);
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM