0

This is what I have:

<div class="container>
    <div class="parent1"></div>
    <div class="parent2">
         <div class="child1"></div>
         <div class="child2"></div>
    </div>
</div>

This is what I want:

<div class="container>
    <div class="parent2">
         <div class="child1"></div>
              <div class="parent1"></div>
         <div class="child2"></div>
    </div>
</div>

Is this possible with only CSS or JavaScript (no jQuery)? Even if the HTML doesn't move, as long as they appear in that order on the page that would be perfect.

AmigaAbattoir
  • 632
  • 8
  • 21
Charles
  • 57
  • 4
  • Both are possible, but it deppends what you are trying to achive. JS can change the html strcuture as you want. But if you want only css, it depends on the expected output – Gerardo BLANCO Jul 02 '18 at 16:10
  • https://stackoverflow.com/questions/41424994/how-to-add-a-div-between-two-divs-by-javascript – abney317 Jul 02 '18 at 16:14

3 Answers3

1

With Javascript:

//Remove the parent 1 div from the container div
 document.getElementsByClassName('container')[0].removeChild(document.getElementsByClassName('parent1')[0]);

//Insert into div between children
const parent2 = document.getElementsByClassName('parent2')[0];
let divEle = document.createElement('div');
divEle.className = 'parent1';
parent2.insertBefore(divEle, parent2.querySelector('.child2'));
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
1

To make this work, I would advise that you remove the div.parent2 around the child classes. Therefore the code becomes

<div class="container parent">
 <div clas="parent1"></div>
 <div class="child1"></div>
 <div class="child2></div>
</div>

then you can use flexbox to do this

.parent{display: flex};
.child1{order:1}
.parent1{order:2}
1

You can do it with Javascript: document.querySelector('.child1').appendChild(document.querySelector('.parent1'));
Demo:

function reorder() {
  document.querySelector('.child1').appendChild(document.querySelector('.parent1'));
}
.container * {
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;
}
.parent1 {
  color: red;
  border-color: red;
}
.child1 {
  color: blue;
  border-color: blue;
}
<div class="container">
<div class="parent1">I'm parent 1!</div>
<div class="parent2">
    I'm parent 2!
         <div class="child1 ">I'm child 1!</div>
         <div class="child2 ">I'm child 2!</div>
    </div>
</div>
<button onclick='reorder();'>Reorder!</button>
Note: Css is only for better looks
bru02
  • 360
  • 2
  • 10