I could find many examples for removing the wrapper element completely in all mode, few options are here,
1. Under cq:Component, add the property cq:noDecoration = true. or
2. Under cq:Component, create a node cq:htmlTag as nt:unstructured & add the property cq:tagName = ""
Now, let see the solution for unwrapping the element only in the preview mode.
The following code is created by AEM for a simple button component named as custom_button & remember this is a sightly component.
<div class="custom_button">
</div>
<div class="custom_button"> - This is the element wrapper created by AEM with the component name that we create. Its main purpose is to add the edit feature for this component. This wrapper is tied up with the overylay elements & properties. It helps to open the dialog box for editing. So, removing this wrapper will hide the editing feature.
<a class="q-button button primary" title="Button Label" target="_self"> - This is part of my html code. Only this element appears in the publish instance. Usually, we write all scripts & css for this element.
I have the javascript file as listener added to my head.html in the base template & it is the base template for all other templates. It makes the JS loaded in all other templates.
----------------------------------------------------------------------------------------------------------------------
var unWrapElementInPreviewMode= function() {
$('iframe').bind("load",function(){
//check if button component exists
var $unWrapSelector = $(this).contents().find('a.x-button');
if($unWrapSelector.length){
$(document).on("click", ".js-editor-LayerSwitcherTrigger", function () {
if($.cookie('wcmmode') == "preview") {
$unWrapSelector.each(function(index,val){
$(this).unwrap();
});
}else{
location.reload();
}
});
}
});
};
$(document).ready(function() {
//refresh page while shifting between Edit and Preview Mode
unWrapElementInPreviewMode();
});
---------------------------------------------------------------------------------------------------------------------
($.cookie('wcmmode') == "preview" - finding the wcmmode. You can see my previous post that covers this in detail.
click listener triggers while clicking the edit or preview button. unwrap() removes the parent element of the selectors and then I'm just reloading the page in edit mode to get my wrapper back. This might add some loading time while shifting from preview to edit mode.