I want to paste some rich text which has different fonts, font sizes, font weights, etc. into a content-editable div
and ONLY keep boldness and italics. Any ide
Here's a working demo: http://jsfiddle.net/SJR3H/7/
$(document).ready(function(){
$('[contenteditable]').on('paste',function(e) {
e.preventDefault();
var text = (e.originalEvent || e).clipboardData.getData('text/html') || prompt('Paste something..');
var $result = $('').append($(text));
$(this).html($result.html());
// replace all styles except bold and italic
$.each($(this).find("*"), function(idx, val) {
var $item = $(val);
if ($item.length > 0){
var saveStyle = {
'font-weight': $item.css('font-weight'),
'font-style': $item.css('font-style')
};
$item.removeAttr('style')
.removeClass()
.css(saveStyle);
}
});
// remove unnecesary tags (if paste from word)
$(this).children('style').remove();
$(this).children('meta').remove()
$(this).children('link').remove();
});
});
Later edit: http://jsfiddle.net/SJR3H/8/
i added the following lines:
$item.replaceWith(function(){
return $("", {html: $(this).html()});
});
It actually replaces all html
tags with span
s. There you can optionally choose to let some tags as they were in the original text (h1
, p
, etc), styling them as you desire.