Naomi S
Naomi S

Reputation: 57

Move an child html elements in javascript loop using insertAfter

I have a repeating chunk of HTML and would like to reorder the child elements using JQuery / Javascript: looking to move the description underneath the button in this simplified version.

The snippet shows roughly my logic but not working like this. Anyone able to fix this?

var licount = $(".tile-group").length;
var children = $(".tile-group").children;

for (i = 0; i < children.length; i++) {
    var child = children[i];
    var desc = child.querySelector(".desc");

    child.insertAfter( desc );
}
.tile {
 margin: 20px;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tile-group">
<div class="tile">
   <div class="title">
      Title 1
   </div>
   <div class="desc">
      Description 1
   </div>
   <div class="btn">
    <button>Button 1</button>
   </div>
</div>
<div class="tile">
   <div class="title">
      Title 2
   </div>
   <div class="desc">
      Description 2
   </div>
   <div class="btn">
    <button>Button 2</button>
   </div>
</div>
</div>

Upvotes: 0

Views: 60

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35011

desc is not the elements' id. It is their class. You should do

var desc = child.querySelector(".desc");

Upvotes: 0

Related Questions