Im using wagtail and i have added a button to the richtext editor that adds 'pre' tag to selected text once the button is clicked, but im struggling to create the code to unwrap the text. Similar to what Joss has done here: https://jossingram.wordpress.com/2014/07/24/add-some-blockquote-buttons-to-wagtail-cms-wysiwyg-editor/
So basically like the bold or italics does once highlighted if it already has a 'pre' tag before remove it if not, then add it. i have tried using parentElement and parentNode and other functions but for some reason the lastSelection function returns an undefined value and it doesn't want to work.
(function() {
(function($) {
return $.widget("IKS.prebutton", {
options: {
uuid: '',
editable: null
},
populateToolbar: function(toolbar) {
var button, widget;
widget = this;
button = $('<span></span>');
button.hallobutton({
uuid: this.options.uuid,
editable: this.options.editable,
label: 'Pre Tag',
icon: 'fa fa-backward',
command: null
});
toolbar.append(button);
return button.on("click", function(event) {
var insertionPoint, lastSelection;
lastSelection = widget.options.editable.getSelection();
insertionPoint = $(lastSelection.endContainer).parentsUntil('.richtext').last();
var elem;
elem = "<pre>" + lastSelection + "</pre>";
if ($(lastSelection).find('pre').length) {
console.log('Selected Word Contains Pre')
// add function to remove tag
}else{
console.log('No Pre Tag in Selected Word')
var node = lastSelection.createContextualFragment(elem);
lastSelection.deleteContents();
lastSelection.insertNode(node);
return widget.options.editable.element.trigger('change');
}
});
}
});
})(jQuery);
}).call(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>