StudioTime
StudioTime

Reputation: 23959

Move position of an item in the DOM

Lets say I have 6 items in a container:

<div class="container">
  <div class="one" style="left:100px">...</div>
  <div class="two" style="left:200px">...</div>
  <div class="three" style="left:300px">...</div>
</div>

Is it possible to change the dom to read:

<div class="container">
  <div class="one" style="left:100px">...</div>
  <div class="three" style="left:300px">...</div>
  <div class="two" style="left:200px">...</div>
</div>

I am trying something different with a masonry layout and need to move things based on size and then re-layout the container. I can't just change the inline style to move them because that would create a gap and when then doing a re-layout the masonry code sees the DOM as it was and then moves them back.

So ideally something like:

$(".container > .item").each(function(){
  // if this class="three" then move its
  // outerHTML and insert it after class="one"
}

Not sure if this is possible.

The basic problem is that I'm building a masonry layout but more like a windows metro look, horizontal as much as vertical, so want gaps filling with elements which maybe further down the list in the DOM

Upvotes: 1

Views: 442

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use insertAfter() to achieve this. Also, if you're specifically targeting .three the loop is redundant. Try this:

$(".container > .three").insertAfter('.one');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="one" style="left:100px">ONE</div>
  <div class="two" style="left:200px">TWO</div>
  <div class="three" style="left:300px">THREE</div>
</div>

Upvotes: 2

antyrat
antyrat

Reputation: 27765

Yes, it's possible. You can use insertAfter method for example:

$( '.container > .three' ).insertAfter( '.container > .one' );

No need to use each method.

Upvotes: 3

Related Questions