Skip to content

Instantly share code, notes, and snippets.

@oleksmarkh
Last active December 20, 2015 07:39
Show Gist options
  • Save oleksmarkh/6094452 to your computer and use it in GitHub Desktop.
Save oleksmarkh/6094452 to your computer and use it in GitHub Desktop.
a simple jquery plugin that wraps styled tags with specified tags
(function ($){
$.fn.wrapInHtml = function (options) {
var tags = $.extend({i: {css: 'font-style',
val: 'italic'},
b: {css: 'font-weight',
val: 'bold'},
u: {css: 'text-decoration',
val: 'underline'}},
options);
return this.each(function () {
var $node = $(this);
$.each(tags, function (tag, prop) {
if (prop === undefined) { return; }
if (prop.val === $node.css(prop.css)) {
$node.css(prop.css, '');
if ($node.is(tag)) { return; }
$node.wrap('<' + tag + '>');
}
});
$node.children().wrapInHtml(tags);
});
};
$.justHtml = function (str, options) {
var $root = $('<p>').html(str);
return $root.wrapInHtml(options).html();
};
})(jQuery);
// usage
var $input = $('some-selector'),
$output = $('another-selector'),
justHtml = $.justHtml($input.html(), {i: null,
em: {css: 'font-style',
val: 'italic'}});
$output.html(justHtml);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment