<div class="wrap">
<h2>JavaScript unwrap children</h2>
<p>Remove green parent div and leave child divs in page.</p>
<p>A JavaScript substitute for <code>display:contents;</code> in all browsers.<br>How can this script be run with a media query or based on screen widths?</p>
<p><b>Reduce Browser Window to kick in media query</b><br> Firefox 56+ will use <code>display:contents;</code>.</p>
<div class="sidebar remove">
<div class="child">child div to remain in page</div>
<div class="child">child div to remain in page</div>
<div class="child">child div to remain in page</div>
</div>
</div>
/* check for display:contents support */
detect {
display:none
}
@supports ( display: contents ) {
detect {
display:block;
}
}
.wrap {
width:90%;
max-width:1000px;
margin:auto;
padding:20px;
outline:1px solid red;
box-sizing: border-box;
}
.sidebar {
margin:10px 0;
padding:40px;
background:lime;
}
.child {
background:#eee;
margin:10px 0;
padding:10px;
}
@media all and (max-width: 760px) {
.remove {
display:contents;
}
}
(function() {
// detect CSS display:contents support by checking elements display as it is set to block in css supports rule
var newEl = document.createElement("detect");
document.body.appendChild(newEl);
if (getComputedStyle(newEl).getPropertyValue("display") === "none") {
//first save html so we can re-instate it
var oldHtml = document.querySelector('.sidebar').cloneNode(true);
function unwrap(sidebar) {
oldHtml = document.querySelector('.sidebar').cloneNode(true);
// place childNodes in document fragment
var docFrag = document.createDocumentFragment();
while (sidebar.firstChild) {
var child = sidebar.removeChild(sidebar.firstChild);
docFrag.appendChild(child);
}
// replace sidebar with document fragment
sidebar.parentNode.replaceChild(docFrag, sidebar);
}
function wrap(child, parent, children) {
parent.insertBefore(oldHtml, child, children);
var i;
for (i = 0; i < children.length; ++i) {
children[i].remove();
}
}
var mql = window.matchMedia("screen and (max-width: 760px)")
mediaqueryresponse(mql) // call listener function explicitly at run time
mql.addListener(mediaqueryresponse) // attach listener function to listen in on state changes
function mediaqueryresponse(mql) {
if (mql.matches) {
unwrap(document.querySelector('.sidebar'));
} else {
if (document.querySelector('.sidebar')) return;
wrap(document.querySelector('.child'), document.querySelector('.wrap'), document.querySelectorAll('.child'));
}
}
}
})();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.