Sanidhay Sanidhay - 2 months ago 8
CSS Question

Add all elements after first element to a div by using javascript (No jQuery)

I have the following html

<div id="main">
<aside id="list"><p>sometext</p></aside>
<aside id="list-2"><p>sometext</p></aside>
<aside id="list-3"><p>sometext</p></aside>
<aside id="list-4"><p>sometext</p></aside>
</div>


I want to use javascript to make it look like :

<div id="main">
<aside id="list"><p>sometext</p></aside>
<div id="wrap">
<aside id="list-2"><p>sometext</p></aside>
<aside id="list-3"><p>sometext</p></aside>
<aside id="list-4"><p>sometext</p></aside>
</div>
</div>


I have tried insertAdjacentHTML and innerHTML methods :

widgets = document.getElementById('main');
widgets.innerHTML = "<div class='box-class'>" + widgets.innerHTML + "</div>";


But this adds wrapper over "list" too.

Answer

There are two big problems with the code you said you tried (three if widgets isn't declared anywhere):

widgets = document.getElementById('main');
widgets.innerHTML = "<div class='box-class'>" + widgets.innerHTML + "</div>";
  1. Using strings means the browser has to go through the elements, build an HTML string for them, and return that string to JavaScript; then when you assign to innerHTML it has to destroy the elements that are already there and build new replacement ones by parsing the HTML string. This will wipe out any event handlers or similar attached to the elements. (Of course, if there aren't any, it doesn't matter much.)
  2. That wraps all of the children, not just the ones after the first child.

(It also wraps them in <div class='box-class'>, not <div id="wrap">, but...)

On all modern browsers, elements have a children list you can use for this. Then just create a wrapper, move the children other than the first into it, and append it.

var main = document.getElementById("main");
var wrapper = document.createElement("div");
wrapper.id = "wrap";
while (main.children.length > 1) {
    // Note: Appending the element to a new parent removes it from its original
    // parent, so `main.children.length` will decrease by 1
    wrapper.appendChild(main.children[1]);
}
main.appendChild(wrapper);

Example:

var main = document.getElementById("main");
var wrapper = document.createElement("div");
wrapper.id = "wrap";
while (main.children.length > 1) {
  wrapper.appendChild(main.children[1]);
}
main.appendChild(wrapper);
#wrap {
  border: 1px solid blue;
}
<div id="main">
  <aside id="list">
    <p>sometext</p>
  </aside>
  <aside id="list-2">
    <p>sometext</p>
  </aside>
  <aside id="list-3">
    <p>sometext</p>
  </aside>
  <aside id="list-4">
    <p>sometext</p>
  </aside>
</div>


Side note: In your markup, you have </div> where you want </aside>.