Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to wrap multiple elements with a parent container in JavaScript

I want to wrap the header, main and footer elements in a container div created with JavaScript. In other words I want to insert a container div as a direct child of the body element but have it wrap all of body's children.

@import url( 'https://necolas.github.io/normalize.css/latest/normalize.css' );

::selection {
  background-color: #fe0;
  color: #444;
}

* {
  box-sizing: border-box;
  margin: 0;
}

html, body {
  height: 100%;
}

header, main, footer {
  height: 30%;
  margin-bottom: 1%;
  background-color: #444;
}

p {
  color: #ccc;
  text-align: center;
  position:relative;
  top: 50%;
  transform: translateY( -50% );
}

.container {
  height: 90%;
  padding: 2%;
  background-color: #eee;
}
<html>
  <body>

    <header>
      <p>header</p>
    </header>
    
    <main>
      <p>main</p>
    </main>
    
    <footer>
      <p>footer</p>
    </footer>

  </body>
</html>

I've seen this done with single elements utilizing replaceChild(), but not with multiple elements as is here. I would like to not use jquery here.

Ideas?

like image 453
Lynel Hudson Avatar asked Oct 24 '25 05:10

Lynel Hudson


1 Answers

  • Create a new div

  • Obtain a nodeList with document.querySelectorAll

  • Use Array#forEach.call on the nodeList to iterate through it and append each element to the newly created div

  • Append the new div to the body:

The code would look something like this:

var newElem = document.createElement('div')
newElem.textContent = 'newElem';

Array.prototype.forEach.call(document.querySelectorAll('header, main, footer'), function(c){
  newElem.appendChild(c);
});
document.body.appendChild(newElem);

JSBIN here

like image 123
Pineda Avatar answered Oct 25 '25 18:10

Pineda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!